package org.jeecgframework.web.controller;

import com.mybatis.ext.WiseCoreService;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.TreeGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.easyui.TreeGridModel;
import org.jeecgframework.web.service.*;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author onlineGenerator
 * @version V1.0
 * @Title: Controller
 * @Description: 服务单
 * @date 2017-12-19 15:10:19
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsServiceController")
public class CbsServiceController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CbsServiceController.class);
    @Autowired
    private CbsServiceAssignListServiceI cbsServiceAssignListServiceI;
    @Autowired
    private CbsServiceServiceI cbsServiceService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private ZyContactsServiceI zyContactsService;
    @Autowired
    private ZyFileLogServiceI zyFileLogServiceI;
    @Autowired
    private CbsServiceLogServiceI cbsServiceLogServiceI;
    @Autowired
    private ZyEsItemServiceI zyEsItemServiceI;
    @Autowired
    private ZyCommonService zyCommonService;
    @Autowired
    private CbsAttachTaskServiceI cbsAttachTaskService;
    @Autowired
    private CbsServiceAssignListServiceI cbsServiceAssignListService;
    @Autowired
    private WiseCoreService wiseCoreService;
    @Autowired
    private CbsReturnEquipmentServiceI cbsReturnEquipmentServiceI;
    @Autowired
    private CbsReturnEquipmentDetailServiceI cbsReturnEquipmentDetailServiceI;
    @Autowired
    private CbsHandleLogServiceI cbsHandleLogServiceI;
    @Autowired
    private CbsServiceTaskMapServiceI cbsServiceTaskMapServiceI;
    @Autowired
    private CbsInspectionEvaluateServiceI cbsInspectionEvaluateService;
    @Autowired
    private CbsDelinerServiceI cbsDelinerService;
    @Autowired
    private WxCommonService wxCommonService;
    @Autowired
    private CbsServiceErrorLogServiceI cbsServiceErrorLogService;
    private CbsServiceEntity cbsService;
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public CbsServiceEntity getCbsService() {
        return cbsService;
    }

    public void setCbsService(CbsServiceEntity cbsService) {
        this.cbsService = cbsService;
    }

    public CbsHandleLogServiceI getCbsHandleLogServiceI() {
        return cbsHandleLogServiceI;
    }

    public void setCbsHandleLogServiceI(CbsHandleLogServiceI cbsHandleLogServiceI) {
        this.cbsHandleLogServiceI = cbsHandleLogServiceI;
    }

    /**
     * 服务单管理 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "cbsService")
    public ModelAndView cbsService(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbsservice/cbsServiceList");
    }

    /**
     * 服务单管理 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "cbsServiceForCSA")
    public ModelAndView cbsServiceForCSA(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbsservice/cbsServiceList-CSA");
    }

    /**
     * 服务单管理 页面跳转(CSA待办列表)
     *
     * @return
     */
    @RequestMapping(params = "cbsServiceFoodorCSATodo")
    public ModelAndView cbsServiceFoodorCSATodo(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbsservice/cbsServiceList-CSATodo");
    }

    /**
     * 服务单管理 页面跳转(所有组织机构是巴可的用户，首页要显示服务单待办)
     *
     * @return
     */
    @RequestMapping(params = "cbsServiceFoodorBaKeTodo")
    public ModelAndView cbsServiceFoodorBaKeTodo(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbsservice/cbsServiceList-BaKeTodo");
    }


    @RequestMapping(params = "goAdd")
    public ModelAndView add(HttpServletRequest request) {
        //根据字典表查询知识类别
        List<TSType> dataList = TSTypegroup.allTypes.get(StaticValue.special_Case.toLowerCase());
        request.setAttribute("dataList", dataList);
        List<TSTerritory> territoryList = systemService.findHql("from TSTerritory where territoryLevel = 1 order by territorySort");
        request.setAttribute("territoryList", territoryList);

        return new ModelAndView("com/zybk/cbsservice/cbsService-add");
    }


    /**
     * @param cityParentId 父级id
     * @param level        级别 1 2 3
     * @return json
     * @author xiul
     * 2016-3-28 下午5:55:24
     * Description 服务类型级联
     */
    @RequestMapping(params = "queryTerritory")
    @ResponseBody
    public AjaxJson queryTerritory(
            @RequestParam(value = "cityParentId", defaultValue = "", required = false) String cityParentId,
            @RequestParam(value = "level", defaultValue = "") Short level) {
        AjaxJson j = new AjaxJson();
        try {
            String sql = "SELECT * FROM cbs_service_type WHERE type = " + level;
            if (cityParentId.equals("")) {
                sql += " AND ISNULL(PARENT_ID) ";
            } else {
                sql += " AND PARENT_ID = '" + cityParentId + "'";
            }
            List<Map<String, Object>> rsMap = systemService.findForJdbc(sql);
            j.setObj(rsMap);
            j.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            j.setSuccess(false);
            j.setMsg("获取省市信息失败！");
        }
        return j;
    }

    /**
     * @param cityParentId 父级id
     * @param level        级别 1 2 3
     * @return json
     * @author xiul
     * 2016-3-28 下午5:55:24
     * Description 故障分类级联
     */
    @RequestMapping(params = "queryError")
    @ResponseBody
    public AjaxJson queryError(
            @RequestParam(value = "cityParentId", defaultValue = "", required = false) String cityParentId,
            @RequestParam(value = "level", defaultValue = "") Short level) {
        AjaxJson j = new AjaxJson();
        try {
            String sql = "SELECT * FROM CBS_ERROR_TYPE WHERE type = " + level;
            if (cityParentId.equals("")) {
                sql += " AND ISNULL(PARENT_ID) ";
            } else {
                sql += " AND PARENT_ID = '" + cityParentId + "'";
            }
            List<Map<String, Object>> rsMap = systemService.findForJdbc(sql);
            j.setObj(rsMap);
            j.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            j.setSuccess(false);
            j.setMsg("获取省市信息失败！");
        }
        return j;
    }

    /**
     * @param cityParentId 父级id
     * @param level        级别 0 1 2
     * @return json
     * @author xiul
     * 2016-3-28 下午5:55:24
     * Description 关键备件故障分类
     */
    @RequestMapping(params = "queryEquipment")
    @ResponseBody
    public AjaxJson queryEquipment(
            @RequestParam(value = "cityParentId", defaultValue = "", required = false) String cityParentId,
            @RequestParam(value = "level", defaultValue = "") Short level) {
        AjaxJson j = new AjaxJson();
        try {
            String sql = "SELECT * FROM CBS_EQUIPMENT_ERROR_TYPE WHERE type = " + level;
            if (cityParentId.equals("")) {
                sql += " AND ISNULL(PARENT_ID) ";
            } else {
                sql += " AND PARENT_ID = '" + cityParentId + "'";
            }
            List<Map<String, Object>> rsMap = systemService.findForJdbc(sql);
            j.setObj(rsMap);
            j.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            j.setSuccess(false);
            j.setMsg("获取省市信息失败！");
        }
        return j;
    }


    /*根据客户电话获取客户信息*/
    @ResponseBody
    @RequestMapping(params = "getInformation")
    public AjaxJson getInformation(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String phone = request.getParameter("phone");
        List<ZyContactsEntity> zyContactsList = zyContactsService.getAddressByPhone(phone);
        if (zyContactsList.size() > 0) {
            ZyContactsEntity zyContactsEntity = zyContactsList.get(0);
            ZyCinemaEntity zyCinemaEntity = zyContactsEntity.getBelongCinema();
            HashMap<String, Object> m = new HashMap<String, Object>();
            m.put("email", zyContactsEntity.getEmail());
            m.put("contactName", zyContactsEntity.getName());
            if (null != zyCinemaEntity) {
                m.put("belongCinema", zyCinemaEntity.getName());
                m.put("fullAddress", zyCinemaEntity.getAddress());
            } else {
                m.put("belongCinema", "");
                m.put("fullAddress", "");
            }

            if (StringUtil.isNotEmpty(zyContactsEntity) && StringUtil.isNotEmpty(zyContactsEntity.getTsBaseUser()) && StringUtil.isNotEmpty(zyContactsEntity.getTsBaseUser().getAuthenticationLevel())) {
                if (zyContactsEntity.getTsBaseUser().getAuthenticationLevel().equals("2")) {
                    m.put("level", "钻石");
                } else if (zyContactsEntity.getTsBaseUser().getAuthenticationLevel().equals("1")) {
                    m.put("level", "银牌");
                } else if (zyContactsEntity.getTsBaseUser().getAuthenticationLevel().equals("3")) {
                    m.put("level", "待审批");
                } else if (zyContactsEntity.getTsBaseUser().getAuthenticationLevel().equals("0")) {
                    m.put("level", "非微信");
                } else if (zyContactsEntity.getTsBaseUser().getAuthenticationLevel().equals("4")) {
                    m.put("level", "金牌");
                }
            } else {
                m.put("level", "非微信");
            }
            ajaxJson.setAttributes(m);
        } else {
            ajaxJson.setSuccess(false);
        }
        return ajaxJson;
    }


    /*根据设备序列号获取设备信息*/
    @ResponseBody
    @RequestMapping(params = "getProjector")
    public AjaxJson getProjector(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String sn = request.getParameter("sn");
        if (StringUtil.isNotEmpty(sn)) {
        	HashMap<String, Object> map = new HashMap<String, Object>();
            //根据设备序列号获取设备信息
            List<Map<String, Object>> list = cbsServiceService.getgetProjector(sn);
            //根据设备序列号获取影院信息
            List<Map<String, Object>> lists = cbsServiceService.getCinemaBySn(sn);
            //获取设备相关历史记录
            List<Map<String, Object>> mapList = cbsServiceService.getAllServiceBySn(sn);
            //获取影院相关历史
            List<Map<String, Object>> cinemaMapList = cbsServiceService.getCinemaList(sn);
            //获取巡检历史
            List<Map<String, Object>> mapList1 = cbsServiceService.getAllPlanBySn(sn);
            //获取sla信息
            List<Map<String, Object>> slaList1 = cbsServiceService.getAllSLABySn(sn);
            //显示当前生效的SLA信息，并且指向SLA增项后的信息标签后，弹框显示所有SLA的标准项列表。
            List<CbsContractEntity> cbsContractList = new ArrayList<>();
            if (slaList1.size() > 0) {
                String supplement = "";
                if (StringUtil.isNotEmpty(slaList1.get(0))) {
                    supplement = (String) slaList1.get(0).get("supplement");
                }
                if (StringUtil.isNotEmpty(supplement)) {
                    String[] suppmentSplit = supplement.split(",");
                    StringBuffer stringBuffer = new StringBuffer();
                    for (int i = 0; i < suppmentSplit.length; i++) {
                        if (!" ".equals(suppmentSplit[i])) {
                            stringBuffer.append(suppmentSplit[i] + ",");
                        }
                    }
                    if (stringBuffer.toString().length() > 1) {
                        slaList1.get(0).put("supplement", stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1));
                    } else if (stringBuffer.toString().length() == 1) {
                        slaList1.get(0).put("supplement", stringBuffer.toString());
                    } else {
                        slaList1.get(0).put("supplement", "");
                    }
                }
                //显示当前生效的SLA信息，并且指向SLA增项后的信息标签后，弹框显示所有SLA的标准项列表。
                List<Map<String, Object>> list1 = cbsServiceService.getSLABySn(sn);
                if (list1.size() > 0) {
                    String[] serviceNames = list1.get(0).get("serviceName").toString().split(",");
                    String[] descriptions = list1.get(0).get("description").toString().split(",");
                    for (int i = 0; i < serviceNames.length; i++) {
                        CbsContractEntity cbsContract = new CbsContractEntity();
                        cbsContract.setServiceName(serviceNames[i]);
                        cbsContract.setDescription(descriptions[i]);
                        cbsContractList.add(cbsContract);
                    }
                }
            }
            map.put("cbsContractList", cbsContractList);
            map.put("projectorlist", list);
            map.put("cinemalist", lists);
            map.put("cbsservicelist", mapList);
            map.put("cinemaMapList", cinemaMapList);
            map.put("zyInspectionPlanList", mapList1);
            map.put("slaList1", slaList1);
            ajaxJson.setAttributes(map);
        }

        return ajaxJson;
    }

    @RequestMapping(params = "saveServiceAndMessage")
    @ResponseBody
    public AjaxJson saveServiceAndMessage(HttpServletRequest request, HttpServletResponse response) {
        //发送短信通知
        String serviceId = request.getParameter("serviceId");  //服务单id
        String phone = request.getParameter("phone").trim();  //联系人电话
        /*服务单受理成功，发送短信通知  */
        if (StringUtil.isNotEmpty(serviceId) && StringUtil.isNotEmpty(phone)) {
            CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, serviceId);
            if (StringUtil.isNotEmpty(cbsServiceEntity)) {
                Map<String, Object> paraMap = new HashMap<String, Object>();
                paraMap.put("sn", StringUtil.isNotEmpty(cbsServiceEntity.getSn()) ? cbsServiceEntity.getSn() : cbsServiceEntity.getSnServer());
                paraMap.put("code", cbsServiceEntity.getCode());
                SendMessage.sendSMSFTL(phone, "message_send_addcbsservcice.ftl", paraMap, systemService);
            }
        }
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.setSuccess(true);
        ajaxJson.setMsg("保存并发送短信成功！");
        return ajaxJson;
    }

    //发送邮件通知
    @RequestMapping(params = "saveServiceAndEmail")
    @ResponseBody
    public AjaxJson saveServiceAndEmail(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        String phone = request.getParameter("phone");  //邮箱
        String htmlText = request.getParameter("htmlText");  //内容
        //发送邮件
        //发送附件邮件
        String subject = "服务单发送邮件";
        try {
            SendMailUtil.sendeMail(phone, subject, htmlText, systemService);
            ajaxJson.setMsg("发送成功");
        } catch (Exception e) {
            ajaxJson.setMsg("发送失败！");
        }

        return ajaxJson;
    }

    /**
     * 根据sn查找设备id
     *
     * @return
     */
    @RequestMapping(params = "getZyEquipmentBySn")
    @ResponseBody
    public AjaxJson getZyEquipmentBySn(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String sn = request.getParameter("sn");
        //根据影院名称。查找影院信息
        if (StringUtil.isNotEmpty(sn)) {
            List<Map<String, Object>> zyEquipmentEntityList = cbsServiceService.getZyEquipmentBySn(sn);
            if (zyEquipmentEntityList.size() == 1) {
                ajaxJson.setSuccess(true);
                ajaxJson.setObj(zyEquipmentEntityList.get(0).get("id"));
            } else {
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg("设备详情不存在");
            }
        } else {
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("设备sn不能为空");
        }
        return ajaxJson;
    }

    /**
     * 根据影院名称，查找是否有影院id
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "getZyCinemaByName")
    @ResponseBody
    public AjaxJson getZyCinemaByName(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String name = request.getParameter("name");
        //根据影院名称。查找影院信息
        if (StringUtil.isNotEmpty(name)) {
            List<Map<String, Object>> zyCinemaEntityList = cbsServiceService.getZyCinemaByName(name);
            if (zyCinemaEntityList.size() == 1) {
                ajaxJson.setSuccess(true);
                ajaxJson.setObj(zyCinemaEntityList.get(0).get("id"));
            } else {
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg("影院详情不存在");
            }
        } else {
            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("影院名称不能为空");
        }
        return ajaxJson;
    }

    /**
     * 保存服务单
     *
     * @param request
     * @param
     * @return
     */
    @RequestMapping(params = "saveService")
    @ResponseBody
    public AjaxJson saveService(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        boolean flag = false;
        boolean flagService = false;
        message = "保存成功！";
        TSUser user = ResourceUtil.getSessionUserName();
        String serviceData = request.getParameter("serviceData");
        JSONObject json = JSONObject.fromObject(serviceData);
        try {
            CbsServiceEntity cbsService = new CbsServiceEntity();
            //设备序列号不存在
            if (StringUtil.isNotEmpty(json.getString("sn").trim())) {
                cbsService.setSn(json.getString("sn").trim());
                List<ZyEquipmentSpareEntity> zyEquipmentSpareList = systemService.findByProperty(ZyEquipmentSpareEntity.class, "sn", json.getString("sn").trim()); //设备id
                if (StringUtil.isNotEmpty(zyEquipmentSpareList) && zyEquipmentSpareList.size() > 0) {
                    ZyEquipmentSpareEntity zyEquipmentSpare = zyEquipmentSpareList.get(0);
                    Date repairEndDate = zyEquipmentSpareList.get(0).getRepairEndDate();
                    cbsService.setZyEquipmentSpareId(zyEquipmentSpare);//设备信息
                    cbsService.setRepairEndDate(repairEndDate); //保修截止日期
                } else {
                	if (json.getString("sn").trim().length() > 1) {
                		flag = true;  //设备序列号不存在
                	}
                }
            }
            if (StringUtil.isNotEmpty(json.getString("snServer").trim())) {
                cbsService.setSnServer(json.getString("snServer").trim());
                List<ZyEquipmentSpareEntity> zyEquipmentSpareListService = systemService.findByProperty(ZyEquipmentSpareEntity.class, "sn", json.getString("snServer").trim()); //服务器id
                if (StringUtil.isNotEmpty(zyEquipmentSpareListService) && zyEquipmentSpareListService.size() > 0) {
                    ZyEquipmentSpareEntity zyEquipmentSpareService = zyEquipmentSpareListService.get(0);
                    Date repairEndDateService = zyEquipmentSpareListService.get(0).getRepairEndDate();
                    cbsService.setZyEquipmentSpareServiceId(zyEquipmentSpareService); //服务器信息
                    cbsService.setRepairEndDateService(repairEndDateService); //保修截止日期
                } else {
                	if ( json.getString("snServer").trim().length() > 1) {
                		flagService = true; //设备序列号不存在
                	}
                }
            }

            if (StringUtil.isNotEmpty(json.getString("topItemSn"))) { //设备机型
                cbsService.setTypeDec(json.getString("topItemSn"));
            } else if (cbsService.getZyEquipmentSpareId() != null) {
            	cbsService.setTypeDec(cbsService.getZyEquipmentSpareId().getType().getTypeDesc());
            }

            //影院所在的省
            TSTerritory province = null;
            if (StringUtil.isNotEmpty(json.getString("province"))) {
                province = systemService.get(TSTerritory.class, json.getString("province"));  //省
                cbsService.setProvince(province);
            }

            //影院所在的市
            TSTerritory city = null;
            if (StringUtil.isNotEmpty(json.getString("city"))) {
                city = systemService.get(TSTerritory.class, json.getString("city"));  //市
                cbsService.setCity(city);
            }

            if (StringUtil.isNotEmpty(json.get("serviceType1"))) {
                CbsServiceTypeEntity cbsServiceType1 = systemService.get(CbsServiceTypeEntity.class, json.getString("serviceType1"));
                cbsService.setServiceType1(cbsServiceType1);
            }
            if (StringUtil.isNotEmpty(json.get("serviceType2"))) {
                CbsServiceTypeEntity cbsServiceType2 = systemService.get(CbsServiceTypeEntity.class, json.getString("serviceType2"));
                cbsService.setServiceType2(cbsServiceType2);
            }
            if (StringUtil.isNotEmpty(json.get("errorType1"))) {
                CbsErrorTypeEntity cbsErrorTypeEntity1 = systemService.get(CbsErrorTypeEntity.class, json.getString("errorType1"));
                cbsService.setErrorType1(cbsErrorTypeEntity1);
            }
            if (StringUtil.isNotEmpty(json.get("errorType2"))) {
                CbsErrorTypeEntity cbsErrorTypeEntity2 = systemService.get(CbsErrorTypeEntity.class, json.getString("errorType2"));
                cbsService.setErrorType2(cbsErrorTypeEntity2);
            }
            if (StringUtil.isNotEmpty(json.get("equipmentErrorType1"))) {
                CbsEquipmentErrorTypeEntity cbsEquipmentErrorTypeEntity1 = systemService.get(CbsEquipmentErrorTypeEntity.class, json.getString("equipmentErrorType1"));
                cbsService.setEquipmentErrorType1(cbsEquipmentErrorTypeEntity1);
            }
            System.out.println(json.get("equipmentErrorType1"));
            if (StringUtil.isNotEmpty(json.get("equipmentErrorType2"))) {
                CbsEquipmentErrorTypeEntity cbsEquipmentErrorTypeEntity2 = systemService.get(CbsEquipmentErrorTypeEntity.class, json.getString("equipmentErrorType2"));
                cbsService.setEquipmentErrorType2(cbsEquipmentErrorTypeEntity2);
            }

            if (StringUtil.isNotEmpty(json.getString("zyCinemaName"))) {
                cbsService.setZyCinemaName(json.getString("zyCinemaName"));
                //根据影院名称。查找影院信息
                List<Map<String, Object>> zyCinemaEntityList = cbsServiceService.getZyCinemaByName(json.getString("zyCinemaName"));
                if (zyCinemaEntityList.size() == 1) {
                    ZyCinemaEntity zyCinemaEntity = systemService.get(ZyCinemaEntity.class, zyCinemaEntityList.get(0).get("id").toString());
                    cbsService.setZyCinemaId(zyCinemaEntity);
                }
            }

            cbsService.setContactsPhone(json.getString("phone").trim());
            cbsService.setContactsName(json.getString("contactName").trim());
            cbsService.setEmail(json.getString("email").trim());
            cbsService.setQq(json.getString("qq"));
            cbsService.setCode(json.getString("code"));
            cbsService.setAddress(json.getString("zyCinemaAddress"));
            cbsService.setSourceType(json.getString("sourceType"));
            cbsService.setClient(json.getString("client"));
            cbsService.setDescription(json.getString("description"));
            cbsService.setJudge400(json.getString("judge400"));
            if (StringUtil.isNotEmpty(json.getString("sourceType")) && json.getString("sourceType").equals(StaticValue.HdType)) {
                cbsService.setStatus(StaticValue.ysl);
            } else {
                cbsService.setStatus(StaticValue.dcl);
            }
            cbsService.setSpeedStatus(StaticValue.dfp);
            cbsService.setErrorCode(json.getString("errorCode"));
            cbsService.setLevel(json.getString("level"));
            cbsService.setCaseFlag(json.getString("specialCase"));
            cbsService.setHdClose(json.getInt("speciallyHD"));
            cbsService.setSpecial(json.getInt("specially"));
            cbsService.setTypename(json.getString("typename"));
//            cbsService.setHandleDes((StringUtil.isNotEmpty(json.getString("description")) ? (json.getString("description") + ";") : "") + (StringUtil.isNotEmpty(json.getString("judge400")) ? (json.getString("judge400") + ";") : "")); //巴可400处理过程
            cbsService.setPersonLiable(user);  //责任人为当前登录人
//            cbsService.setCreateBy(user.getUserName());
            systemService.saveOrUpdate(cbsService);
            //服务单日志
            cbsServiceLogServiceI.addServiceLog(cbsService, StaticValue.Close_Service_Log_Type_2, user.getRealName() + "创建服务单成功。", null);
            String speciallyFile = json.getString("speciallyFile");  //特批文件id
            String errorphone = json.getString("errorphone");  //故障照片文件id
            if (StringUtil.isNotEmpty(speciallyFile)) {
                for (String s : speciallyFile.split(",")) {
                    ZyFileLogEntity zyFileLogEntity = zyFileLogServiceI.get(ZyFileLogEntity.class, s);
                    zyFileLogEntity.setBusinessKey(cbsService.getId());
                    zyFileLogEntity.setBusinessChildType(StaticValue.Business_File_Type_B);
                    zyFileLogServiceI.save(zyFileLogEntity);
                    //服务处理日志
                    CbsServiceLogEntity cbsServiceLogEntity = new CbsServiceLogEntity();
                    cbsServiceLogEntity.setCbsServiceId(cbsService);
                    cbsServiceLogEntity.setLogType(1);
                    cbsServiceLogEntity.setDescription("上传特批文件");
                    cbsServiceLogEntity.setZyFileLogId(zyFileLogEntity);
                    systemService.save(cbsServiceLogEntity);
                }
            }
            if (StringUtil.isNotEmpty(errorphone)) {
                for (String s : errorphone.split(",")) {
                    ZyFileLogEntity zyFileLogEntity1 = zyFileLogServiceI.get(ZyFileLogEntity.class, s);
                    zyFileLogEntity1.setBusinessKey(cbsService.getId());
                    zyFileLogEntity1.setBusinessChildType(StaticValue.Business_File_Type_A);
                    zyFileLogServiceI.save(zyFileLogEntity1);
                    //服务处理日志
                    CbsServiceLogEntity cbsServiceLogEntity = new CbsServiceLogEntity();
                    cbsServiceLogEntity.setCbsServiceId(cbsService);
                    cbsServiceLogEntity.setLogType(1);
                    cbsServiceLogEntity.setDescription("上传故障照片");
                    cbsServiceLogEntity.setZyFileLogId(zyFileLogEntity1);
                    systemService.save(cbsServiceLogEntity);
                }
            }

            //设备序列号不存在，添加异常记录
            if (flag && StringUtil.isNotEmpty(cbsService)) {
                cbsServiceErrorLogService.doAdd(cbsService, json.getString("sn"), "无设备序列号");

            }
            if (flagService && StringUtil.isNotEmpty(cbsService)) {
                cbsServiceErrorLogService.doAdd(cbsService, json.getString("snServer"), "无服务器序列号");
            }

            //调用微信接口发送
            List<Map<String, String>> list = new ArrayList<>();
            String content = "尊敬的客户：您的放映机<" + json.getString("sn") + ">的服务申请已受理，服务单号：<" + json.getString("code") + ">。我们会尽快为您处理。【中影巴可客服部】";
            if (StringUtil.isNotEmpty(json.getString("phone"))) {
                List<TSUser> user1 = systemService.findByProperty(TSUser.class, "mobilePhone", json.getString("phone"));
                if (user1 != null && user1.size() > 0) {
                    if (StringUtil.isNotEmpty(user1.get(0).getOpenId())) {
                        Map<String, String> map = new HashMap<>();
                        map.put("openid", user1.get(0).getOpenId());
                        map.put("message", content);
                        list.add(map);
                        wxCommonService.sendMsgForWx(list);
                    }
                }
            }

            /*******************************************************************************end*/


            Map map1 = new HashMap();
            map1.put("serviceId", cbsService.getId());
            ajaxJson.setAttributes(map1);
            ajaxJson.setMsg(message);

        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.setMsg("保存失败");
            ajaxJson.setSuccess(false);
        }
        return ajaxJson;
    }

    /*修改服务单*/
    @RequestMapping(params = "updateService")
    @ResponseBody
    public AjaxJson updateService(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        boolean flag = false;
        message = "保存成功！";
        TSUser user = ResourceUtil.getSessionUserName();
        String serviceData = request.getParameter("serviceData");
        JSONObject json = JSONObject.fromObject(serviceData);

        try {
            ZyContactsEntity zyContacts = null;//联系人
            List<ZyContactsEntity> zyContactsList = systemService.findByProperty(ZyContactsEntity.class, "cellphone1", json.getString("phone").trim()); //联系人信息；
            if (zyContactsList.size() > 0) {
                zyContacts = zyContactsList.get(0);
            }

            TSTerritory province = null;
            if (StringUtil.isNotEmpty(json.getString("province"))) {
                province = systemService.get(TSTerritory.class, json.getString("province"));  //省
            }

            TSTerritory city = null;
            if (StringUtil.isNotEmpty(json.getString("city"))) {
                city = systemService.get(TSTerritory.class, json.getString("city"));  //市
            }


            ZyEquipmentSpareEntity zyEquipmentSpare = null;//设备信息
            ZyEquipmentSpareEntity zyEquipmentSpareService = null;//影院信息信息
            List<ZyEquipmentSpareEntity> zyEquipmentSpareList = null;
            List<ZyEquipmentSpareEntity> zyEquipmentSpareEntities = null;
            ZyCinemaEntity zyCinemaId = null; //所属影院id；
            if (StringUtil.isNotEmpty(json.getString("sn"))) {
                zyEquipmentSpareList = systemService.findByProperty(ZyEquipmentSpareEntity.class, "sn", json.getString("sn").trim()); //设备id
            }
            if (StringUtil.isNotEmpty(json.getString("snServer"))) {
                zyEquipmentSpareEntities = systemService.findByProperty(ZyEquipmentSpareEntity.class, "sn", json.getString("snServer").trim()); //服务器id
            }
            if (StringUtil.isNotEmpty(zyEquipmentSpareList) && zyEquipmentSpareList.size() > 0) {
                zyEquipmentSpare = zyEquipmentSpareList.get(0);
                zyCinemaId = zyEquipmentSpareList.get(0).getZyCinema();
                if (null == zyCinemaId && StringUtil.isNotEmpty(zyEquipmentSpareEntities)) {
                    zyCinemaId = zyEquipmentSpareEntities.get(0).getZyCinema();
                    zyEquipmentSpareService = zyEquipmentSpareEntities.get(0);
                }
            } else {
            	if (StringUtil.isNotEmpty(json.getString("sn")) && json.getString("sn").trim().length()>1 ) {
                    flag = true;
            	}
            }

            CbsServiceTypeEntity cbsServiceType1 = null;
            CbsServiceTypeEntity cbsServiceType2 = null;
            CbsErrorTypeEntity cbsErrorTypeEntity1 = null;
            CbsErrorTypeEntity cbsErrorTypeEntity2 = null;
            CbsEquipmentErrorTypeEntity cbsEquipmentErrorTypeEntity1 = null;
            CbsEquipmentErrorTypeEntity cbsEquipmentErrorTypeEntity2 = null;
            if (StringUtil.isNotEmpty(json.get("serviceType1"))) {
                cbsServiceType1 = systemService.get(CbsServiceTypeEntity.class, json.getString("serviceType1"));
            }
            if (StringUtil.isNotEmpty(json.get("serviceType2"))) {
                cbsServiceType2 = systemService.get(CbsServiceTypeEntity.class, json.getString("serviceType2"));
            }
            if (StringUtil.isNotEmpty(json.get("errorType1"))) {
                cbsErrorTypeEntity1 = systemService.get(CbsErrorTypeEntity.class, json.getString("errorType1"));
            }
            if (StringUtil.isNotEmpty(json.get("errorType2"))) {
                cbsErrorTypeEntity2 = systemService.get(CbsErrorTypeEntity.class, json.getString("errorType2"));
            }
            if (StringUtil.isNotEmpty(json.get("equipmentErrorType1"))) {
                cbsEquipmentErrorTypeEntity1 = systemService.get(CbsEquipmentErrorTypeEntity.class, json.getString("equipmentErrorType1"));
            }
            if (StringUtil.isNotEmpty(json.get("equipmentErrorType2"))) {
                cbsEquipmentErrorTypeEntity2 = systemService.get(CbsEquipmentErrorTypeEntity.class, json.getString("equipmentErrorType2"));
            }

            if (StringUtil.isNotEmpty(json.getString("serviceId"))) {
                CbsServiceEntity cbsService = systemService.get(CbsServiceEntity.class, json.getString("serviceId"));
                //获取未修改之前的信息，用于判断是否发送邮件通知
                String level = cbsService.getLevel();
                String authentication = cbsService.getAuthentication();
                String email = cbsService.getEmail();
                String phone1 = cbsService.getContactsPhone();
                String zyContactsName = cbsService.getContactsName();
                String QQ = cbsService.getQq();
                String sn = cbsService.getSn();
                String zyCinemaName = cbsService.getZyCinemaName();
                String typename = cbsService.getTypename();
                String province1 = StringUtil.isNotEmpty(cbsService.getProvince()) ? cbsService.getProvince().getId() : "";
                String city1 = StringUtil.isNotEmpty(cbsService.getCity()) ? cbsService.getCity().getId() : "";
                String address = cbsService.getAddress();


                if (StringUtil.isNotEmpty(cbsService)) {
                    cbsService.setZyCinemaId(zyCinemaId);
                    cbsService.setZyEquipmentSpareId(zyEquipmentSpare);
                    cbsService.setZyEquipmentSpareServiceId(zyEquipmentSpareService);
                    cbsService.setCity(city);
                    cbsService.setProvince(province);
                    cbsService.setErrorType1(cbsErrorTypeEntity1);
                    cbsService.setErrorType2(cbsErrorTypeEntity2);
                    cbsService.setEquipmentErrorType1(cbsEquipmentErrorTypeEntity1);
                    cbsService.setEquipmentErrorType2(cbsEquipmentErrorTypeEntity2);
                    cbsService.setServiceType1(cbsServiceType1);
                    cbsService.setServiceType2(cbsServiceType2);
                    cbsService.setContactsPhone(json.getString("phone").trim());
                    cbsService.setCode(json.getString("code"));
                    cbsService.setSn(json.getString("sn").trim());
                    cbsService.setAddress(json.getString("zyCinemaAddress"));
                    cbsService.setSourceType(json.getString("sourceType"));
                    cbsService.setClient(json.getString("client"));
                    cbsService.setZyCinemaName(json.getString("zyCinemaName"));
                    cbsService.setDescription(json.getString("description"));
                    cbsService.setJudge400(json.getString("judge400"));
                    cbsService.setContactsName(json.getString("contactName").trim());
                    cbsService.setEmail(json.getString("email").trim());
                    cbsService.setQq(json.getString("qq"));
                    cbsService.setErrorCode(json.getString("errorCode"));
                    cbsService.setLevel(json.getString("level"));
                    cbsService.setCaseFlag(json.getString("specialCase"));
                    cbsService.setHdClose(json.getInt("speciallyHD"));
                    cbsService.setSpecial(json.getInt("specially"));
                    cbsService.setTypename(json.getString("typename"));
                    cbsService.setAuthentication(json.getString("authentication"));
                    cbsService.setHandleDes(json.getString("handledes"));
                    cbsService.setAssignDes(json.getString("assignDes"));

                    //待处理状态改为已受理
                    if (json.getString("serviceStatus").equals(StaticValue.dcl) && cbsService.getStatus().equals(StaticValue.dcl)) {
                        cbsService.setStatus(StaticValue.ysl);
                        cbsService.setSpeedStatus(StaticValue.dfp);
                        cbsService.setPersonLiable(user);  //责任人为当前登录人

                        if (StringUtil.isNotEmpty(json.getString("sourceType")) && json.getString("sourceType").equals(StaticValue.weixin)) {
                            //判断服务单是否是维修服务单
                            /*快速保修类型*/
                            String JkType = "";
                            boolean flags = false;

                            CbsServiceTypeEntity sType1 = systemService.singleResult("from CbsServiceTypeEntity where type=0 and name like '%故障维修%'");
                            CbsServiceTypeEntity sType2 = systemService.singleResult("from CbsServiceTypeEntity where type=1 and name like '%普通维修%'");

                            CbsServiceTypeEntity sType3 = systemService.singleResult("from CbsServiceTypeEntity where type=0 and name like '%增值服务%'"); //增值服务类型
                            CbsServiceTypeEntity sType4 = systemService.singleResult("from CbsServiceTypeEntity where type=1 and name like '%引擎翻新%'"); //子单类型是引擎翻新类型
                            CbsServiceTypeEntity sType5 = systemService.singleResult("from CbsServiceTypeEntity where type=1 and name like '%光管翻新%'"); //子单类型是光管翻新类型
                            CbsServiceTypeEntity sType6 = systemService.singleResult("from CbsServiceTypeEntity where type=1 and name like '%移机%'"); //子单类型是移机类型

                            CbsServiceTypeEntity sType7 = systemService.singleResult("from CbsServiceTypeEntity where type=0 and name like '%咨询%'");
                            CbsServiceTypeEntity sType8 = systemService.singleResult("from CbsServiceTypeEntity where type=1 and name like '%维保咨询%'");


                            if (StringUtil.isNotEmpty(cbsService.getServiceType1()) && StringUtil.isNotEmpty(cbsService.getServiceType2())) {

                                if (StringUtil.isNotEmpty(sType1) && StringUtil.isNotEmpty(sType2) && cbsService.getServiceType1().getId().equals(sType1.getId()) && cbsService.getServiceType2().getId().equals(sType2.getId())) {
                                    JkType = StaticValue.KSBXTYPE;
                                    flags = true;
                                }
                                if (StringUtil.isNotEmpty(sType3) && StringUtil.isNotEmpty(sType3) && StringUtil.isNotEmpty(cbsService.getServiceType1()) && StringUtil.isNotEmpty(cbsService.getServiceType2())) {
                                    if (cbsService.getServiceType1().getId().equals(sType3.getId())) {  /*增值服务*/
                                        if (cbsService.getServiceType2().getId().equals(sType4.getId())) {
                                            JkType = StaticValue.YQFXTYPE;
                                            flags = true;
                                        }
                                        if (cbsService.getServiceType2().getId().equals(sType5.getId())) {
                                            JkType = StaticValue.GGFXTYPE;
                                            flags = true;
                                        }
                                        if (cbsService.getServiceType2().getId().equals(sType6.getId())) {
                                            JkType = StaticValue.SBYJTYPE;
                                            flags = true;
                                        }
                                    }
                                }

                                if (StringUtil.isNotEmpty(sType7) && StringUtil.isNotEmpty(sType8) && cbsService.getServiceType1().getId().equals(sType7.getId()) && cbsService.getServiceType2().getId().equals(sType8.getId())) {
                                    JkType = StaticValue.SBWBTYPE;
                                    flags = true;
                                }
                            }

                            if (flags) {
                                //服务单微信提交的已受理加积分
                                List<TSUser> users = systemService.findByProperty(TSUser.class, "userName", cbsService.getCreateBy());
                                if (StringUtil.isNotEmpty(users)) {
                                    for (TSUser tsUser : users) {
                                        if (StringUtil.isNotEmpty(tsUser.getOpenId())) {
                                            wxCommonService.AccRepard(tsUser.getOpenId(), JkType);
                                        }
                                    }
                                }
                                //add start 1109 增加发送微信消息
                                //调用微信接口发送
                                List<Map<String, String>> list = new ArrayList<>();
                                String content = "尊敬的客户：您的放映机<" + json.getString("sn") + ">的服务申请已受理，服务单号：<" + json.getString("code") + ">。我们会尽快为您处理。【中影巴可客服部】";
                                if (StringUtil.isNotEmpty(json.getString("phone"))) {
                                    List<TSUser> user1 = systemService.findByProperty(TSUser.class, "mobilePhone", json.getString("phone"));
                                    if (user1 != null && user1.size() > 0) {
                                        if (StringUtil.isNotEmpty(user1.get(0).getOpenId())) {
                                            Map<String, String> map = new HashMap<>();
                                            map.put("openid", user1.get(0).getOpenId());
                                            map.put("message", content);
                                            list.add(map);
                                            wxCommonService.sendMsgForWx(list);
                                        }
                                    }
                                }
                                //add end 1109 增加发送微信消息
                            }
                        }

                    }

                    systemService.saveOrUpdate(cbsService);
                    message = "保存成功！";
                    //服务单日志
                    cbsServiceLogServiceI.addServiceLog(cbsService, StaticValue.Close_Service_Log_Type_2, "编辑服务单成功。", null);

                    String speciallyFile = json.getString("speciallyFile");  //特批文件id
                    String errorphone = json.getString("errorphone");  //故障照片文件id

                    if (StringUtil.isNotEmpty(speciallyFile)) {
                        for (String s : speciallyFile.split(",")) {
                            ZyFileLogEntity zyFileLogEntity = zyFileLogServiceI.get(ZyFileLogEntity.class, s);
                            if (StringUtil.isNotEmpty(zyFileLogEntity)) {
                                zyFileLogEntity.setBusinessKey(cbsService.getId());
                                zyFileLogEntity.setBusinessChildType(StaticValue.Business_File_Type_B);
                                zyFileLogServiceI.save(zyFileLogEntity);
                            }
                            //服务处理日志
                            List<CbsServiceLogEntity> cbsServiceLogEntityList = cbsServiceLogServiceI.findByProperty(CbsServiceLogEntity.class, "zyFileLogId.id", speciallyFile);
                            if (cbsServiceLogEntityList.size() == 0) {
                                CbsServiceLogEntity cbsServiceLogEntity = new CbsServiceLogEntity();
                                cbsServiceLogEntity.setCbsServiceId(cbsService);
                                cbsServiceLogEntity.setLogType(1);
                                cbsServiceLogEntity.setDescription("上传特批文件");
                                cbsServiceLogEntity.setZyFileLogId(zyFileLogEntity);
                                systemService.save(cbsServiceLogEntity);
                            }
                        }
                    }
                    if (StringUtil.isNotEmpty(errorphone)) {
                        for (String s : errorphone.split(",")) {
                            ZyFileLogEntity zyFileLogEntity1 = zyFileLogServiceI.get(ZyFileLogEntity.class, s);
                            if (StringUtil.isNotEmpty(zyFileLogEntity1)) {
                                zyFileLogEntity1.setBusinessKey(cbsService.getId());
                                zyFileLogEntity1.setBusinessChildType(StaticValue.Business_File_Type_A);
                                zyFileLogServiceI.save(zyFileLogEntity1);
                            }
                            //服务处理日志
                            List<CbsServiceLogEntity> cbsServiceLogEntityList = cbsServiceLogServiceI.findByProperty(CbsServiceLogEntity.class, "zyFileLogId.id", speciallyFile);
                            if (cbsServiceLogEntityList.size() == 0) {
                                CbsServiceLogEntity cbsServiceLogEntity = new CbsServiceLogEntity();
                                cbsServiceLogEntity.setCbsServiceId(cbsService);
                                cbsServiceLogEntity.setLogType(1);
                                cbsServiceLogEntity.setDescription("上传故障照片");
                                cbsServiceLogEntity.setZyFileLogId(zyFileLogEntity1);
                                systemService.save(cbsServiceLogEntity);
                            }
                        }
                    }


                    //服务单状态如果为“处理中”，当修改客户信息、设备信息、服务优先级、工程师等级要求变更时
                    if (StringUtil.isNotEmpty(json.getString("serviceStatus")) && json.getString("serviceStatus").equals(StaticValue.clz)) {
                        boolean f = false;
                        //联系人手机号
                        if (!f && !phone1.equals(json.getString("phone"))) {
                            f = true;
                        }
                        //邮箱
                        if (!f && !email.equals(json.getString("email"))) {
                            f = true;
                        }
                        //姓名
                        if (!f && !zyContactsName.equals(json.getString("contactName"))) {
                            f = true;
                        }
                        //QQ号
                        if (!f && !QQ.equals(json.getString("qq"))) {
                            f = true;
                        }
                        /*sn号修改*/
                        if (!f && !sn.equals(json.getString("sn"))) {
                            f = true;
                        }
                        /*影院名称修改*/
                        if (!f && !zyCinemaName.equals(json.getString("zyCinemaName"))) {
                            f = true;
                        }
                        /*影院地址修改*/
                        if (!f && !address.equals(json.getString("zyCinemaAddress"))) {
                            f = true;
                        }
                        if (!f && !province1.equals(json.getString("province"))) {
                            f = true;
                        }
                        if (!f && !city1.equals(json.getString("city"))) {
                            f = true;
                        }
                        /*院线修改*/
                        if (!f && !typename.equals(json.getString("typename"))) {
                            f = true;
                        }
                        /*修改了服务优先级*/
                        if (!f && !level.equals(json.getString("level"))) {
                            f = true;
                        }
                        /*修改工程师等级*/
                        if (!f && !authentication.equals(json.get("authentication"))) {
                            f = true;
                        }
                        if (f) {
                            //向服务商商务 和 工程师发送服务单变更通知
                            String code = cbsService.getCode();
                            String zyCinemaName1 = cbsService.getZyCinemaName();
                            String serviceType = "";
                            if (StringUtil.isNotEmpty(cbsService.getServiceType2())) {
                                serviceType = cbsService.getServiceType2().getName();
                            }
                            String sn1 = cbsService.getSn();
                            String type = "";
                            List<ZyEquipmentSpareEntity> esList = systemService.findHql("from ZyEquipmentSpareEntity where sn = ?", sn1);
                            if (esList.size() > 0) {
                                type = esList.get(0).getType().getTypeDesc();
                            }
                            String description = cbsService.getDescription();
                            String zyContactsName1 = cbsService.getContactsName();
                            String phone = cbsService.getContactsPhone();
                            String level1 = cbsService.getLevel();
                            String authentication1 = cbsService.getAuthentication();

                            SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
                            /*邮件*/
                            //第三方商务id
                            if (StringUtil.isNotEmpty(cbsService.getZyContacts())) {
                                ZyContactsEntity zyContacts1 = systemService.get(ZyContactsEntity.class, cbsService.getZyContacts());
                                ZyEmailEntity eMail = new ZyEmailEntity();

                                /*短信*/
                                Map<String, Object> paraMap = new HashMap<String, Object>();
                                paraMap.put("contacterName", zyContacts1.getBelongOrg().getShortname());
                                paraMap.put("code", code);
                                SendMessage.sendSMSFTL(zyContacts1.getCellphone1(), "message_change_service.ftl", paraMap, systemService);


                                String s = "巴可服务单变更：" + level1 + "-" + serviceType + "-" + code + "-" + zyCinemaName1 + "-" + sdf.format(new Date()) + "";
                                eMail.setEmailSubject(s);
                                eMail.setEmailReceiver(zyContacts1.getEmail());
                                Map<String, Object> paraMap1 = new HashMap<String, Object>();
                                paraMap1.put("contacterName", zyContacts1.getBelongOrg().getShortname());
                                paraMap1.put("code", code);
                                paraMap1.put("type", type);
                                paraMap1.put("sn", sn1);
                                paraMap1.put("description", description);
                                paraMap1.put("level", level1);
                                paraMap1.put("authentication", authentication1);
                                paraMap1.put("zyCinemaName", zyCinemaName1);
                                paraMap1.put("zyContactsName", zyContactsName1);
                                paraMap1.put("phone", phone);

                                if (StringUtil.isNotEmpty(zyContacts1.getEmail())) {
                                    /*商务*/
                                    SendMailUtil.sendFtlMail(eMail, "mail_change_service.ftl", paraMap1, systemService);
                                }


                                /*APP通知*/
                                CbsAppMessageEntity appMessage = new CbsAppMessageEntity();
                                String content = "您的服务单" + code + "发生变更，可在“我的任务”中查看详情。";
                                appMessage.setContent(content);
                                appMessage.setSender(user.getId());
                                TSBaseUser baseUser = systemService.get(TSBaseUser.class, zyContacts1.getTsBaseUser().getId());
                                appMessage.setReciver(baseUser.getId());
                                appMessage.setState(StaticValue.DIC_APP_MESSAGE_STATE_UNREAD);
                                systemService.save(appMessage);
                                systemService.addLog("新增APP消息,接受方:" + baseUser.getId() + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);


                                /*工程师*/
                                if (StringUtil.isNotEmpty(cbsService.getEngineer())) {
                                    ZyEngineerEntity zyEngineer1 = systemService.get(ZyEngineerEntity.class, cbsService.getEngineer());
                                    ZyEmailEntity eMail1 = new ZyEmailEntity();
                                    eMail1.setEmailSubject(s);
                                    eMail1.setEmailReceiver(zyEngineer1.getEmail());
                                    /*工程师*/
                                    SendMessage.sendSMSFTL(zyEngineer1.getCellphone(), "message_change_service.ftl", paraMap, systemService);
                                    if (StringUtil.isNotEmpty(zyEngineer1.getEmail())) {
                                        SendMailUtil.sendFtlMail(eMail1, "mail_change_service.ftl", paraMap1, systemService);
                                    }

                                    /*APP通知*/
                                    TSBaseUser baseUser1 = systemService.get(TSBaseUser.class, zyEngineer1.getTsBaseUser().getId());
                                    appMessage.setReciver(baseUser1.getId());
                                    appMessage.setState(StaticValue.DIC_APP_MESSAGE_STATE_UNREAD);
                                    systemService.save(appMessage);
                                    systemService.addLog("新增APP消息,接受方:" + baseUser1.getId() + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);

                                }
                            }
                        }
                    }

                    // 投诉功能！保存成功后，判断编辑的单子是否是投诉子单，且父单是否是投诉子单，
                    // 且除本单外是否父类下还有投诉子单，如果有，发送短信通知
//                    if (cbsServiceService.getServiceTypeNameByServiceId(json.getString("serviceId"))) {
//                        //邮件通知客户支持经理
//                        ZyEmailEntity eMail = new ZyEmailEntity();
//                        eMail.setEmailSubject("投诉邮件");
//                        eMail.setEmailReceiver("bingyue_zhang@asdc.com.cn");
//                        Map<String, Object> paraMap = new HashMap<String, Object>();
//                        SendMailUtil.sendFtlMail(eMail, "mail_complain.ftl", paraMap, systemService);
//                    }

                }


                //设备序列号不存在，添加异常记录
                if (flag && StringUtil.isNotEmpty(cbsService)) {
                    cbsServiceErrorLogService.doAdd(cbsService, json.getString("sn"), "无设备序列号");
                }

                Map map = new HashMap();
                map.put("serviceId", cbsService.getId());
                ajaxJson.setAttributes(map);


            } else {
                ajaxJson.setSuccess(false);
                message = "服务单信息不存在！";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ajaxJson.setMsg(message);
        return ajaxJson;
    }


    /**
     * 弹框提示设备序列和影院名称
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "goInfo")
    public ModelAndView goInfo(HttpServletRequest req) {
        String sn = req.getParameter("sn");
        String zyCinemaName = req.getParameter("zyCinemaName");
        req.setAttribute("sn", sn);
        req.setAttribute("zyCinemaName", zyCinemaName);
        return new ModelAndView("com/zybk/cbsservice/goInfo");
    }

    /**
     * 弹框提示短信模板和手机号
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "goInfoMessage")
    public ModelAndView goInfoMessage(HttpServletRequest req) {
        String sn = req.getParameter("sn");
        String code = req.getParameter("code");
        String phone = req.getParameter("phone");
        String serviceId = req.getParameter("serviceId");
        Map<String, Object> paraMap = new HashMap<String, Object>();
        paraMap.put("sn", sn);
        paraMap.put("code", code);
        String htmlText = SendMessage.getSMSFTL(phone, "message_send_addcbsservcice.ftl", paraMap, systemService);
        req.setAttribute("htmlText", htmlText);
        req.setAttribute("phone", phone);
        req.setAttribute("serviceId", serviceId);
        return new ModelAndView("com/zybk/cbsservice/goInfoMessage");
    }

    /**
     * 服务单发送邮件
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "sendMessage")
    public ModelAndView sendMessage(HttpServletRequest req) {
        req.setAttribute("serviceId", req.getParameter("id"));
        return new ModelAndView("com/zybk/cbsservice/sendMessage");
    }

    //获取服务单号
    @RequestMapping(params = "getNo")
    @ResponseBody
    public AjaxJson getNo(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        Map m = new HashMap();
        m = cbsServiceService.getNo();
        j.setAttributes(m);
        return j;
    }

    @RequestMapping(params = "getServiceType")
    @ResponseBody
    public AjaxJson getServiceType(HttpServletRequest request, HttpServletResponse response) {
        String serviceType1 = request.getParameter("serviceType1");
        AjaxJson j = new AjaxJson();
        if (StringUtil.isNotEmpty(serviceType1)) {
            CbsServiceTypeEntity cbsServiceTypeEntity = systemService.get(CbsServiceTypeEntity.class, serviceType1);
            if (StringUtil.isNotEmpty(cbsServiceTypeEntity)) {
                if (cbsServiceTypeEntity.getName().equals("咨询")) {
                    j.setSuccess(false);
                }
            }
        }
        return j;
    }

    /**
     * 服务单导出
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportInspectionPlan")
    public void exportInspectionPlan(HttpServletRequest request, HttpServletResponse response) {
        //创造一个session属性来判断导出的遮罩层是否应该隐藏
        request.getSession().setAttribute("shadeKey", "loading");
        cbsServiceService.exportInspectionPlan(request, response);
        request.getSession().removeAttribute("shadeKey");
    }

    @RequestMapping(params = "getShadeKey")
    @ResponseBody
    public int getShadeKey(HttpServletRequest request, HttpServletResponse response) {
        Object shadeKey = request.getSession().getAttribute("shadeKey");
        if (StringUtil.isNotEmpty(shadeKey) && "loading".equals(shadeKey.toString())) {
            return 1;
        }
        return 0;
    }


    /**
     * 服务商商务，区域，工程师 导出服务单
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportInspectionAssignList")
    public void exportInspectionAssignList(HttpServletRequest request, HttpServletResponse response) {
        //创造一个session属性来判断导出的遮罩层是否应该隐藏
        request.getSession().setAttribute("shadeKey", "loading");
        cbsServiceService.exportInspectionAssignList(request, response);
        request.getSession().removeAttribute("shadeKey");

    }

    /**
     * 克隆
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "clone")
    public AjaxJson clone(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        TSUser user = ResourceUtil.getSessionUserName();
        String id = request.getParameter("id");
        try {
            CbsServiceEntity cbsService = systemService.get(CbsServiceEntity.class, id);
            if (null != cbsService) {
                CbsServiceEntity cbs = new CbsServiceEntity();
                if (StringUtil.isNotEmpty(cbsService.getZyCinemaId())) {
                    cbs.setZyCinemaId(cbsService.getZyCinemaId());//影院id
                }
                cbs.setTypename(cbsService.getTypename());
                cbs.setZyCinemaName(cbsService.getZyCinemaName());
                cbs.setContactsPhone(cbsService.getContactsPhone()); //联系人id
                cbs.setContactsName(cbsService.getContactsName());
                cbs.setQq(cbsService.getQq());
                cbs.setSourceType(StaticValue.HdType); //HD新建，默认
                cbs.setSpeedStatus(StaticValue.dfp);
                cbs.setStatus(StaticValue.ysl);
                cbs.setEmail(cbsService.getEmail());
                cbs.setSn(cbsService.getSn());  /*设备SN*/
                cbs.setTypeDec(cbsService.getTypeDec());
                cbs.setZyEquipmentSpareId(cbsService.getZyEquipmentSpareId()); /*设备序列号*/
                cbs.setZyEquipmentSpareServiceId(cbsService.getZyEquipmentSpareServiceId());
                cbs.setProvince(cbsService.getProvince());
                cbs.setCity(cbsService.getCity());
                cbs.setAddress(cbsService.getAddress());
                cbs.setLevel(cbsService.getLevel());
                cbs.setServiceType1(StringUtil.isNotEmpty(cbsService.getServiceType1()) ? cbsService.getServiceType1() : null);
                cbs.setServiceType2(StringUtil.isNotEmpty(cbsService.getServiceType2()) ? cbsService.getServiceType2() : null);
                cbs.setEquipmentErrorType1(StringUtil.isNotEmpty(cbsService.getEquipmentErrorType1()) ? cbsService.getEquipmentErrorType1() : null);
                cbs.setEquipmentErrorType2(StringUtil.isNotEmpty(cbsService.getEquipmentErrorType2()) ? cbsService.getEquipmentErrorType2() : null);
                cbs.setErrorType1(StringUtil.isNotEmpty(cbsService.getErrorType1()) ? cbsService.getErrorType1() : null);
                cbs.setErrorType2(StringUtil.isNotEmpty(cbsService.getErrorType2()) ? cbsService.getErrorType2() : null);
                Map m = cbsServiceService.getNo();
                cbs.setCode(m.get("no").toString());
                cbs.setPersonLiable(user);
                systemService.saveOrUpdate(cbs);

                //服务单日志
                cbsServiceLogServiceI.addServiceLog(cbs, StaticValue.Close_Service_Log_Type_2, "服务单由" + cbsService.getCode() + "克隆生成。", null);
            }

            ajaxJson.setMsg("克隆成功！");

        } catch (Exception e) {

            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("克隆失败！");

        }


        return ajaxJson;
    }

    /**
     * 创建子单
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "createSublist")
    public AjaxJson createSublist(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        TSUser user = ResourceUtil.getSessionUserName();
        String id = request.getParameter("id");
        try {
            CbsServiceEntity cbsService = systemService.get(CbsServiceEntity.class, id);
            if (null != cbsService) {
                String code = cbsService.getCode();
                String[] s = code.split("-");
                if (s.length == 1) {
                    CbsServiceEntity cbs = new CbsServiceEntity();
                    // 复制数据
                    if (StringUtil.isNotEmpty(cbsService.getZyCinemaId())) {
                        cbs.setZyCinemaId(cbsService.getZyCinemaId());//影院id
                    }
                    cbs.setTypename(cbsService.getTypename());
                    cbs.setZyCinemaName(cbsService.getZyCinemaName());
                    cbs.setContactsPhone(cbsService.getContactsPhone()); //联系人id
                    cbs.setContactsName(cbsService.getContactsName());
                    cbs.setQq(cbsService.getQq());
                    cbs.setSourceType(StaticValue.HdType); //HD新建，默认
                    cbs.setSpeedStatus(StaticValue.dfp);
                    cbs.setStatus(StaticValue.ysl);
                    cbs.setEmail(cbsService.getEmail());
                    cbs.setSn(cbsService.getSn());  /*设备SN*/
                    cbs.setZyEquipmentSpareId(cbsService.getZyEquipmentSpareId()); /*设备序列号*/
                    cbs.setZyEquipmentSpareServiceId(cbsService.getZyEquipmentSpareServiceId());
                    cbs.setProvince(cbsService.getProvince());
                    cbs.setCity(cbsService.getCity());
                    cbs.setAddress(cbsService.getAddress());
                    cbs.setCode(cbsServiceService.getSublistNo(code).get("code").toString());
                    cbs.setPersonLiable(user);
                    systemService.saveOrUpdate(cbs);
                    ajaxJson.setMsg("子单创建成功！");

                    //**日志
                    cbsServiceLogServiceI.addServiceLog(cbs, StaticValue.Close_Service_Log_Type_2, "该单由：" + user.getRealName() + "根据" + cbsService.getCode() + "生成的子单", null);

                } else {
                    ajaxJson.setSuccess(false);
                    ajaxJson.setMsg("此单已经是子单，不能再次创建子单");
                }
            }

        } catch (Exception e) {

            ajaxJson.setSuccess(false);
            ajaxJson.setMsg("创建失败！");

        }


        return ajaxJson;
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        Map param = new HashMap<>();
        boolean flag = false; //页面查询条件为空时不做查询
        String status1 = request.getParameter("status1");
        String speedstatus1 = request.getParameter("speedstatus1");
        String belongCinemaId = request.getParameter("belongCinemaId");

        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String key : parameterMap.keySet()) {
            if (key.equals("_territoryL2") || key.equals("_territoryL3") || key.equals("_serviceType1") ||
                    key.equals("assignType") || key.equals("belongCinemaId") ||
                    key.equals("code") || key.equals("assignType") ||
                    key.equals("SR") || key.equals("SO") ||
                    key.equals("offerno") || key.equals("approStatus") ||
                    key.equals("sn") || key.equals("names") ||
                    key.equals("personliable") || key.equals("createname") ||
                    key.equals("intheaterName") || key.equals("address") ||
                    key.equals("sourceType") || key.equals("serviceProvider") ||
                    key.equals("status1") || key.equals("phone") ||
                    key.equals("speedstatus1") || key.equals("createDate_begin") ||
                    key.equals("createDate_end") || key.equals("closeTime_begin") ||
                    key.equals("closeTime_end") || key.equals("_serviceType2") ||
                    key.equals("serviceTypeName") || key.equals("year") || key.equals("month")) {
                if (!StringUtil.isEmpty(parameterMap.get(key)[0])) {
                    flag = true;//页面 查询条件为空不做查询
                    break;
                }
            }
        }
        if (flag) {
            for (Object key : parameterMap.keySet()) {
                if ((String[]) request.getParameterMap().get(key) != null) {
                    for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                        if (((String[]) request.getParameterMap().get(key))[i] != null) {
                            param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
                        }
                    }
                }
            }

            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_begin")))) {
                param.put("createDate_begin", oConvertUtils.getString(param.get("createDate_begin")) + " 00:00:01");
            }
            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_end")))) {
                param.put("createDate_end", oConvertUtils.getString(param.get("createDate_end")) + " 23:59:59");
            }
            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_begin")))) {
                param.put("closeTime_begin", oConvertUtils.getString(param.get("closeTime_begin")) + " 00:00:01");
            }
            if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_end")))) {
                param.put("closeTime_end", oConvertUtils.getString(param.get("closeTime_end")) + " 23:59:59");
            }
            TSUser user = ResourceUtil.getSessionUserName();
            if (StringUtil.isNotEmpty(user)) {
                param.put("userId", user.getId());
            }
            if (StringUtil.isNotEmpty(status1)) {
                List<String> statusList = new ArrayList<>();
                String[] status1Split = status1.split(",");
                for (int i = 0; i < status1Split.length; i++) {
                    if ("".equals(status1Split[i])) {
                        continue;
                    }
                    statusList.add(status1Split[i]);
                }
                param.put("statusList", statusList);
            }
            if (StringUtil.isNotEmpty(speedstatus1)) {
                List<String> speedstatusList = new ArrayList<>();
                String[] speedstatus1Split = speedstatus1.split(",");
                for (int i = 0; i < speedstatus1Split.length; i++) {
                    if ("".equals(speedstatus1Split[i])) {
                        continue;
                    }
                    speedstatusList.add(speedstatus1Split[i]);
                }
                param.put("speedstatusList", speedstatusList);
            }

            if (StringUtil.isNotEmpty(belongCinemaId)) {  //影院id
                param.put("belongCinemaId", belongCinemaId);
            }

            //从院线服务情况报表过来的查询条件
            String year = request.getParameter("year");  //年
            String month = request.getParameter("month");  //月
            String serviceTypeName = request.getParameter("serviceTypeName");  //服务一级分类名字
            String statusList1 = request.getParameter("statusList");
            if (StringUtil.isNotEmpty(year)) {
                param.put("year", year);
            }
            if (StringUtil.isNotEmpty(month)) {
                param.put("month", month);
            }
            if (StringUtil.isNotEmpty(serviceTypeName)) {
                param.put("serviceTypeName", serviceTypeName);
            }
            if (StringUtil.isNotEmpty(statusList1)) {
                String a = statusList1.replace("[", "").replace("]", "");
                String arryList = a.replace(" ", "");
                param.put("statusList", arryList);
            }
            /***************************end*****************************/
            wiseCoreService.selectDataGrid("selectHDserviceDatagrid", param, dataGrid);
        } else {
            //只查 “待处理”“已受理” 的服务单
            param.put("status1", "0");
            String status2 = "1,2";
            List<String> statusList = new ArrayList<>();
            String[] status1Split = status2.split(",");
            for (int i = 0; i < status1Split.length; i++) {
                if ("".equals(status1Split[i])) {
                    continue;
                }
                statusList.add(status1Split[i]);
            }
            param.put("statusList", statusList);
            wiseCoreService.selectDataGrid("selectHDserviceDatagrid", param, dataGrid);
        }

      //查询 关联所需要的 服务类型
        List<Map<String,Object>> serviceTypeMapList = systemService.findForJdbc("select id, name from cbs_service_type");
 
        Map<String, Map> serviceTypeMap = StringUtil.listToMapWithKey(serviceTypeMapList, "id");

        Iterator it = dataGrid.getResults().iterator();
        while(it.hasNext()){
            Map<String, Object> m = (Map<String, Object>)it.next();
          //替换、翻译数据库字段供页面展示
            if (StringUtil.isNotEmpty(m.get("servicetype2")) && serviceTypeMap.get(m.get("servicetype2")) != null) {
                m.put("servicetype2", serviceTypeMap.get(m.get("servicetype2").toString()).get("name"));
            }

        }
        
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * easyui AJAX请求数据csa待办列表
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */

    @RequestMapping(params = "datagridTodo")
    public void datagridTodo(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        Map param = new HashMap<>();
        String status1 = request.getParameter("status1");
        String speedstatus1 = request.getParameter("speedstatus1");
        for (Object key : request.getParameterMap().keySet()) {
            if ((String[]) request.getParameterMap().get(key) != null) {
                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
                        param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
                    }
                }
            }
        }
        if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_begin")))) {
            param.put("createDate_begin", oConvertUtils.getString(param.get("createDate_begin")) + " 00:00:01");
        }
        if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_end")))) {
            param.put("createDate_end", oConvertUtils.getString(param.get("createDate_end")) + " 23:59:59");
        }
        if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_begin")))) {
            param.put("closeTime_begin", oConvertUtils.getString(param.get("closeTime_begin")) + " 00:00:01");
        }
        if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_end")))) {
            param.put("closeTime_end", oConvertUtils.getString(param.get("closeTime_end")) + " 23:59:59");
        }
        TSUser user = ResourceUtil.getSessionUserName();
        if (StringUtil.isNotEmpty(user)) {
            param.put("userId", user.getId());
        }
        if (StringUtil.isNotEmpty(status1)) {
            List<String> statusList = new ArrayList<>();
            String[] status1Split = status1.split(",");
            for (int i = 0; i < status1Split.length; i++) {
                if ("".equals(status1Split[i])) {
                    continue;
                }
                statusList.add(status1Split[i]);
            }
            param.put("statusList", statusList);
        }
        if (StringUtil.isNotEmpty(speedstatus1)) {
            List<String> speedstatusList = new ArrayList<>();
            String[] speedstatus1Split = speedstatus1.split(",");
            for (int i = 0; i < speedstatus1Split.length; i++) {
                if ("".equals(speedstatus1Split[i])) {
                    continue;
                }
                speedstatusList.add(speedstatus1Split[i]);
            }
            param.put("speedstatusList", speedstatusList);
        }
        wiseCoreService.selectDataGrid("selectHDserviceTodoDatagrid", param, dataGrid);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * easyui AJAX请求数据巴可人员待办列表
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */

    @RequestMapping(params = "datagridBaKeTodo")
    public void datagridBaKeTodo(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        Map param = new HashMap<>();
        String status1 = request.getParameter("status1");
        String speedstatus1 = request.getParameter("speedstatus1");
        for (Object key : request.getParameterMap().keySet()) {
            if ((String[]) request.getParameterMap().get(key) != null) {
                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
                        param.put(key, ((String[]) request.getParameterMap().get(key))[i].trim());
                    }
                }
            }
        }
        if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_begin")))) {
            param.put("createDate_begin", oConvertUtils.getString(param.get("createDate_begin")) + " 00:00:01");
        }
        if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("createDate_end")))) {
            param.put("createDate_end", oConvertUtils.getString(param.get("createDate_end")) + " 23:59:59");
        }
        if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_begin")))) {
            param.put("closeTime_begin", oConvertUtils.getString(param.get("closeTime_begin")) + " 00:00:01");
        }
        if (!StringUtil.isEmpty(oConvertUtils.getString(param.get("closeTime_end")))) {
            param.put("closeTime_end", oConvertUtils.getString(param.get("closeTime_end")) + " 23:59:59");
        }
        TSUser user = ResourceUtil.getSessionUserName();
        if (StringUtil.isNotEmpty(user)) {
            param.put("userId", user.getId());
        }
        if (StringUtil.isNotEmpty(status1)) {
            List<String> statusList = new ArrayList<>();
            String[] status1Split = status1.split(",");
            for (int i = 0; i < status1Split.length; i++) {
                if ("".equals(status1Split[i])) {
                    continue;
                }
                statusList.add(status1Split[i]);
            }
            param.put("statusList", statusList);
        }
        if (StringUtil.isNotEmpty(speedstatus1)) {
            List<String> speedstatusList = new ArrayList<>();
            String[] speedstatus1Split = speedstatus1.split(",");
            for (int i = 0; i < speedstatus1Split.length; i++) {
                if ("".equals(speedstatus1Split[i])) {
                    continue;
                }
                speedstatusList.add(speedstatus1Split[i]);
            }
            param.put("speedstatusList", speedstatusList);
        }
        wiseCoreService.selectDataGrid("selectBaKeServiceTodoDatagrid", param, dataGrid);
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 更换责任人
     */
    @ResponseBody
    @RequestMapping(params = "changePerson")
    public AjaxJson changePerson(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            j = cbsServiceService.changePerson(request);
            j.setMsg("转派成功");
        } catch (Exception e) {
            j.setMsg("转派失败");
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }

    private void validateEmail(ZyEmailEntity emailEntity) throws Exception {
        // receiver
        String emailReceiver = emailEntity.getEmailReceiver();
        // title
        String emailSubject = emailEntity.getEmailSubject();

        // to do...
        // temp validate rules
        if (null == emailReceiver) {
            throw new Exception("邮件接收人不能为空！"); // NOPMD by dzqThinkpad on 16-4-1 下午3:01
        }
        if (null == emailSubject) {
            throw new Exception("邮件标题不能为空！"); // NOPMD by dzqThinkpad on 16-4-1 下午3:01
        }
    }

    /**
     * 删除服务单
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(CbsServiceEntity cbsService, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        cbsService = systemService.getEntity(CbsServiceEntity.class, cbsService.getId());
        message = "服务单删除成功";
        try {
            cbsServiceService.delete(cbsService);
            systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        } catch (Exception e) {
            e.printStackTrace();
            message = "服务单删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除服务单
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        message = "服务单删除成功";
        try {
            for (String id : ids.split(",")) {
                CbsServiceEntity cbsService = systemService.getEntity(CbsServiceEntity.class,
                        id
                );
                cbsServiceService.delete(cbsService);
                systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "服务单删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        return new ModelAndView("com/zybk/cbsservice/cbsServiceUpload");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public String exportXls(CbsServiceEntity cbsService, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        CriteriaQuery cq = new CriteriaQuery(CbsServiceEntity.class, dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsService, request.getParameterMap());
        List<CbsServiceEntity> cbsServices = this.cbsServiceService.getListByCriteriaQuery(cq, false);
        modelMap.put(NormalExcelConstants.FILE_NAME, "服务单");
        modelMap.put(NormalExcelConstants.CLASS, CbsServiceEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("服务单管理", "导出人:" + ResourceUtil.getSessionUserName().getRealName(),
                "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, cbsServices);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(CbsServiceEntity cbsService, HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(TemplateExcelConstants.FILE_NAME, "服务单");
        modelMap.put(TemplateExcelConstants.PARAMS, new TemplateExportParams("Excel模板地址"));
        modelMap.put(TemplateExcelConstants.MAP_DATA, null);
        modelMap.put(TemplateExcelConstants.CLASS, CbsServiceEntity.class);
        modelMap.put(TemplateExcelConstants.LIST_DATA, null);
        return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CbsServiceEntity> listCbsServiceEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(), CbsServiceEntity.class, params);
                for (CbsServiceEntity cbsService : listCbsServiceEntitys) {
                    cbsServiceService.save(cbsService);
                }
                j.setMsg("文件导入成功！");
            } catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(ExceptionUtil.getExceptionMessage(e));
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }

    /**
     * 编辑服务单详情页面
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView update(HttpServletRequest req) {

        String id = req.getParameter("id");
        String sn = req.getParameter("sn");
        String code = req.getParameter("code");
        req.setAttribute("cbsCode", code);

        if (StringUtil.isNotEmpty(id)) {
            /*获取编辑页面基本信息*/
            List<Map<String, Object>> mapList = cbsServiceService.getCbsServiceByCid(id);
            req.setAttribute("mapList", mapList.get(0));

            if (StringUtil.isEmpty(sn)) {
                if (StringUtil.isNotEmpty(mapList.get(0).get("sn"))) {
                    sn = mapList.get(0).get("sn").toString();
                } else if (StringUtil.isNotEmpty(mapList.get(0).get("snService"))) {
                    sn = mapList.get(0).get("snService").toString();
                }
            }

            //获取申请的备件
            List<Map<String, Object>> cbsEquipmentApplyEntities = systemService.findForJdbc("SELECT a.id AS id, a.record_id AS code, GROUP_CONCAT(ad.type_des SEPARATOR '\\\\') AS typedes, GROUP_CONCAT(ad.item SEPARATOR '\\\\') AS item, GROUP_CONCAT(ad.total SEPARATOR '\\\\') AS total, a.apply_reason AS reason,a.`status` as `status1`,CASE a.`status` WHEN '1' THEN '待审批' WHEN '2' THEN '审批已通过' WHEN '3' THEN '审批未通过' END `status` FROM CBS_EQUIPMENT_APPLY a LEFT JOIN cbs_equipment_apply_detail ad ON ad.APPLY_ID = a.id WHERE a.service_id ='" + id + "'  GROUP BY record_id");
            if (cbsEquipmentApplyEntities.size() > 0) {
                for (Map<String, Object> cbsEquipmentApplyEntity : cbsEquipmentApplyEntities) {
                    String cbsEq = cbsEquipmentApplyEntity.get("id").toString();
                    List<Map<String, Object>> list = systemService.findForJdbc("select id,is_hb,space_number from cbs_deliver where equipment_apply_id = '" + cbsEquipmentApplyEntity.get("id") + "'");
                    if (list.size() != 0 && "1".equals(list.get(0).get("is_hb"))) {
                        List<String> id_list = systemService.findListbySql("select id from cbs_deliver where space_number like '%" + list.get(0).get("space_number") + "/%' or space_number like '%/" + list.get(0).get("space_number") + "%'");
                        String sql = "SELECT e.id, CASE d.`status` WHEN '1' THEN 'CSA待发货' WHEN '2' THEN 'CSA已发货' WHEN '3' THEN 'CSA取消发货' WHEN '4' THEN '欠货中' WHEN '5' THEN '物流待发货' WHEN '6' THEN '物流已发货' WHEN '7' THEN '签收' END AS `status`, IFNULL( DATE_FORMAT( d.expecttime, '%Y-%m-%d  %H:%i:%s' ), '' ) AS expecttime, IFNULL( DATE_FORMAT( d.gettime, '%Y-%m-%d  %H:%i:%s' ), '' ) AS gettime, d.`code` AS `code`, t.type_desc AS typedes, e.item AS item, IFNULL(d.deliver_logistics, '') AS deliverlogistics, IFNULL( DATE_FORMAT( d.LOGISTICS_SENDTIME, '%Y-%m-%d %H:%i:%s' ), '' ) AS LOGISTICSSENDTIME FROM cbs_deliver_equipment e LEFT JOIN cbs_deliver d ON e.deliver_id = d.id LEFT JOIN cbs_equipment_apply a ON a.id = d.equipment_apply_id LEFT JOIN zy_equipment_type t ON t.id = e.type_id LEFT JOIN zy_es_item m ON m.id = e.item_id WHERE d.id='" + id_list.get(0) + "'";
                        List<Map<String, Object>> deliverEquipmentList = systemService.findForJdbc(sql);
                        cbsEquipmentApplyEntity.put("cbsDeliverEquipmentEntities", deliverEquipmentList);
                    } else {
                        String sql = "SELECT e.id, CASE d.`status` WHEN '1' THEN 'CSA待发货' WHEN '2' THEN 'CSA已发货' WHEN '3' THEN 'CSA取消发货' WHEN '4' THEN '欠货中' WHEN '5' THEN '物流待发货' WHEN '6' THEN '物流已发货' WHEN '7' THEN '签收' END AS `status`, IFNULL( DATE_FORMAT( d.expecttime, '%Y-%m-%d  %H:%i:%s' ), '' ) AS expecttime, IFNULL( DATE_FORMAT( d.gettime, '%Y-%m-%d  %H:%i:%s' ), '' ) AS gettime, d.`code` AS `code`, t.type_desc AS typedes, e.item AS item, IFNULL(d.deliver_logistics, '') AS deliverlogistics, IFNULL( DATE_FORMAT( d.LOGISTICS_SENDTIME, '%Y-%m-%d %H:%i:%s' ), '' ) AS LOGISTICSSENDTIME FROM cbs_deliver_equipment e LEFT JOIN cbs_deliver d ON e.deliver_id = d.id LEFT JOIN cbs_equipment_apply a ON a.id = d.equipment_apply_id LEFT JOIN zy_equipment_type t ON t.id = e.type_id LEFT JOIN zy_es_item m ON m.id = e.item_id WHERE a.id  = '" + cbsEq + "'";
                        List<Map<String, Object>> deliverEquipmentList = systemService.findForJdbc(sql);
                        cbsEquipmentApplyEntity.put("cbsDeliverEquipmentEntities", deliverEquipmentList);
                    }
                }
            }
            req.setAttribute("cbsEquipmentApplyEntities", cbsEquipmentApplyEntities);

            if (StringUtil.isNotEmpty(sn)) {
                //服务单历史
                List<Map<String, Object>> serviceBySn = cbsServiceService.getAllServiceBySn(sn);
                req.setAttribute("serviceBySn", serviceBySn);

                //获取影院相关历史
                List<Map<String, Object>> cinemaMapList = cbsServiceService.getCinemaList(sn);
                req.setAttribute("cinemaMapList", cinemaMapList);

                //巡检历史
                List<Map<String, Object>> allPlanBySn = cbsServiceService.getAllPlanBySn(sn);
                req.setAttribute("allPlanBySn", allPlanBySn);

                //获取sla信息
                List<Map<String, Object>> slaList1 = cbsServiceService.getAllSLABySn(sn);
                String supplement = "";
                if (slaList1.size() > 0) {
                    supplement = (String) slaList1.get(0).get("supplement");
                    if (StringUtil.isNotEmpty(supplement)) {
                        String[] suppmentSplit = supplement.split(",");
                        StringBuffer stringBuffer = new StringBuffer();
                        for (int i = 0; i < suppmentSplit.length; i++) {
                            if (!" ".equals(suppmentSplit[i])) {
                                stringBuffer.append(suppmentSplit[i] + ",");
                            }
                        }
                        if (stringBuffer.toString().length() > 1) {
                            slaList1.get(0).put("supplement", stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1));
                        } else if (stringBuffer.toString().length() == 1) {
                            slaList1.get(0).put("supplement", stringBuffer.toString());
                        } else {
                            slaList1.get(0).put("supplement", null);
                        }
                    }
                    req.setAttribute("slaList1", slaList1.get(0));
                }
                //显示当前生效的SLA信息，并且指向SLA增项后的信息标签后，弹框显示所有SLA的标准项列表。
                List<Map<String, Object>> list = cbsServiceService.getSLABySn(sn);
                if (list.size() > 0) {
                    String[] serviceNames = list.get(0).get("serviceName").toString().split(",");
                    String[] descriptions = list.get(0).get("description").toString().split(",");
                    List<CbsContractEntity> cbsContractList = new ArrayList<>();
                    for (int i = 0; i < serviceNames.length; i++) {
                        CbsContractEntity cbsContract = new CbsContractEntity();
                        cbsContract.setServiceName(serviceNames[i]);
                        cbsContract.setDescription(descriptions[i]);
                        cbsContractList.add(cbsContract);
                    }
                    req.setAttribute("cbsContractList", cbsContractList);
                }
            }


            //文件管理
            List<Map<String, Object>> zyFileLogEntityA = cbsServiceAssignListService.getFileLogByServiceId(id, "A");
            List<Map<String, Object>> zyFileLogEntityB = cbsServiceAssignListService.getFileLogByServiceId(id, "B");
            req.setAttribute("zyFileLogEntityA", zyFileLogEntityA.size() != 0 ? zyFileLogEntityA : null);
            req.setAttribute("zyFileLogEntityB", zyFileLogEntityB.size() != 0 ? zyFileLogEntityB : null);

            //文件上传日志管理
            List<Map<String, Object>> zyFileLogList = cbsServiceLogServiceI.getAllFileByCbsId(id);
            req.setAttribute("zyFileLogList", zyFileLogList);

            //查询
//            List<Map<String, Object>> list = systemService.findForJdbc("SELECT u.realname,cbslog.create_date,cbslog.description,filelog.old_file_name FROM cbs_service AS s,zy_file_log AS filelog,t_s_base_user AS u,cbs_service_log AS cbslog WHERE s.person_liable = u.id AND s.id = filelog.business_key AND cbslog.cbs_service_id = s.id AND cbslog.zy_file_log_id = filelog.id AND s.id = '" + id + "'");
//            req.setAttribute("list", list);
            //查询转派处理描述
            List<CbsHandleLogEntity> cbsHandleLogEntityList = systemService.findHql("from CbsHandleLogEntity where businessId='" + id + "' and logType=3 order by createDate DESC");
            req.setAttribute("cbsHandleLogEntityList", cbsHandleLogEntityList);
            /*获取服务处理日志*/
            List<Map<String, Object>> cbsServiceLogList = cbsServiceLogServiceI.getServiceLog(id);
            req.setAttribute("cbsServiceLogList", cbsServiceLogList);

            //获取关联的父子单
            if (code.split("-").length > 0) {
                code = code.split("-")[0];
            }
            List<CbsServiceEntity> cbsServiceEntityList = systemService.findHql("FROM CbsServiceEntity where code like '%" + code + "%'");
            req.setAttribute("cbsServiceEntityList", cbsServiceEntityList); //关联的父子单

            //是否可以编辑完工单
            req.setAttribute("editServiceReport", cbsServiceService.checkForEditServiceReport(id).isSuccess());

            List<Map<String, Object>> cbsServiceEntities = systemService.findForJdbc("SELECT zy_cinema_id AS zycinemaid, zy_equipment_spare_id AS zyequipmentspareid, person_liable AS personliable, close_user AS closeuser, `status` AS `status`,create_name AS createname FROM cbs_service where id= '" + id + "'");
            for (Map<String, Object> cbsServiceEntity : cbsServiceEntities) {
                req.setAttribute("cbsStatus", StringUtil.isNotEmpty(cbsServiceEntity.get("status")) ? cbsServiceEntity.get("status").toString() : "");
                //附加任务信息
                List<CbsServiceTaskMapEntity> cbsServiceTaskMap = cbsServiceTaskMapServiceI.findByProperty(CbsServiceTaskMapEntity.class, "serviceId.id", id);
                req.setAttribute("attachTaskByCondition", cbsServiceTaskMap);

                if (null != cbsServiceEntity.get("personliable") && cbsServiceEntity.get("personliable") != "" && StringUtil.isNotEmpty(cbsServiceEntity.get("personliable").toString())) {
                    TSUser personLiable = systemService.get(TSUser.class, cbsServiceEntity.get("personliable").toString());
                    String realName = personLiable.getRealName();
                    String userName = personLiable.getId();
                    req.setAttribute("personLiable", realName);
                    req.setAttribute("personId", userName);
                }
                if (StringUtil.isNotEmpty(cbsServiceEntity.get("createname"))) {
                    req.setAttribute("createname", cbsServiceEntity.get("createname"));
                }
                if (StringUtil.isNotEmpty(cbsServiceEntity.get("closeuser"))) {
                    TSUser closeUser = systemService.get(TSUser.class, cbsServiceEntity.get("closeuser").toString());
                    String realName1 = closeUser.getRealName();
                    req.setAttribute("closeUser", realName1);
                }
            }
            List<TSDepart> tsDeparts = systemService.findHql("from TSDepart where orgType = ?", StaticValue.DIC_ORG_TYPE_THIRD_PARTY);
            req.setAttribute("tsDeparts", tsDeparts);


            //获取到货异常
            List<ArrivalofabnormalEntity> arrivalOfAbnormal = systemService.findByProperty(ArrivalofabnormalEntity.class, "serviceId.id", id);

            for (ArrivalofabnormalEntity arrivalofabnormalEntity : arrivalOfAbnormal) {
                String sql = "SELECT id, old_file_name, file_path FROM zy_file_log l WHERE l.business_type = 'g' AND business_key = '" + arrivalofabnormalEntity.getId() + "'";
                List<Map<String, Object>> zyFileLogEntities = systemService.findForJdbc(sql);
                arrivalofabnormalEntity.setZyFileLogEntityList(zyFileLogEntities);
            }
            req.setAttribute("arrivalOfAbnormal", arrivalOfAbnormal);

            //获取故障代码
            List<TSTerritory> territoryList = systemService.findHql("from TSTerritory where territoryLevel = 1 order by territorySort");
            req.setAttribute("territoryList", territoryList);
            List<CbsServiceTypeEntity> serviceTypeList = systemService.findHql("from CbsServiceTypeEntity where type = 0 ");
            req.setAttribute("serviceTypeList", serviceTypeList);
            List<CbsErrorTypeEntity> errorTypeList = systemService.findHql("from CbsErrorTypeEntity where type = 0 ");
            req.setAttribute("errorTypeList", errorTypeList);
            List<CbsEquipmentErrorTypeEntity> equipmentErrorTypeList = systemService.findHql("from CbsEquipmentErrorTypeEntity where type = 0 ");
            req.setAttribute("equipmentErrorTypeList", equipmentErrorTypeList);

            req.getSession().setAttribute("cbsId", id);

        }

        return new ModelAndView("com/zybk/cbsservice/cbsService-update");
    }

    /**
     * CSA角色编辑服务单详情页面
     *
     * @return
     */
    @RequestMapping(params = "goUpdateForCSA")
    public ModelAndView goUpdateForCSA(HttpServletRequest req) {

        String id = req.getParameter("id");
        String sn = req.getParameter("sn");
        String code = req.getParameter("code");
        req.setAttribute("cbsCode", code);

        if (StringUtil.isNotEmpty(id)) {
            /*获取编辑页面基本信息*/
            List<Map<String, Object>> mapList = cbsServiceService.getCbsServiceByCid(id);
            req.setAttribute("mapList", mapList.get(0));

            if (StringUtil.isEmpty(sn)) {
                sn = mapList.get(0).get("sn").toString();
            }

            //获取申请的备件
            List<Map<String, Object>> cbsEquipmentApplyEntities = systemService.findForJdbc("SELECT a.id AS id, a.record_id AS code, GROUP_CONCAT(ad.type_des SEPARATOR '\\\\') AS typedes, GROUP_CONCAT(ad.item SEPARATOR '\\\\') AS item, GROUP_CONCAT(ad.total SEPARATOR '\\\\') AS total, a.apply_reason AS reason,a.`status` as `status1`,CASE a.`status` WHEN '1' THEN '待审批' WHEN '2' THEN '审批已通过' WHEN '3' THEN '审批未通过' END `status` FROM CBS_EQUIPMENT_APPLY a LEFT JOIN cbs_equipment_apply_detail ad ON ad.APPLY_ID = a.id WHERE a.service_id ='" + id + "'  GROUP BY record_id");
            if (cbsEquipmentApplyEntities.size() > 0) {
                for (Map<String, Object> cbsEquipmentApplyEntity : cbsEquipmentApplyEntities) {
                    String cbsEq = cbsEquipmentApplyEntity.get("id").toString();
                    String sql = "SELECT e.id, CASE d.`status` WHEN '1' THEN 'CSA待发货' WHEN '2' THEN 'CSA已发货' WHEN '3' THEN 'CSA取消发货' WHEN '4' THEN '欠货中' WHEN '5' THEN '物流待发货' WHEN '6' THEN '物流已发货' WHEN '7' THEN '签收' END AS `status`, IFNULL( DATE_FORMAT( d.expecttime, '%Y-%m-%d  %H:%i:%s' ), '' ) AS expecttime, IFNULL( DATE_FORMAT( d.gettime, '%Y-%m-%d  %H:%i:%s' ), '' ) AS gettime, d.`code` AS `code`, t.type_desc AS typedes, m.item AS item, IFNULL(d.deliver_logistics, '') AS deliverlogistics, IFNULL( DATE_FORMAT( d.LOGISTICS_SENDTIME, '%Y-%m-%d  %H:%i:%s' ), '' ) AS LOGISTICSSENDTIME FROM cbs_deliver_equipment e LEFT JOIN cbs_deliver d ON e.deliver_id = d.id LEFT JOIN cbs_equipment_apply a ON a.id = d.equipment_apply_id LEFT JOIN zy_equipment_type t ON t.id = e.type_id LEFT JOIN zy_es_item m ON m.id = e.item_id WHERE a.id  = '" + cbsEq + "'";
                    List<Map<String, Object>> deliverEquipmentList = systemService.findForJdbc(sql);
                    cbsEquipmentApplyEntity.put("cbsDeliverEquipmentEntities", deliverEquipmentList);
                }

            }
            req.setAttribute("cbsEquipmentApplyEntities", cbsEquipmentApplyEntities);

            if (StringUtil.isNotEmpty(sn)) {
                //服务单历史
                List<Map<String, Object>> serviceBySn = cbsServiceService.getAllServiceBySn(sn);
                req.setAttribute("serviceBySn", serviceBySn);

                //获取影院相关历史
                List<Map<String, Object>> cinemaMapList = cbsServiceService.getCinemaList(sn);
                req.setAttribute("cinemaMapList", cinemaMapList);

                //巡检历史
                List<Map<String, Object>> allPlanBySn = cbsServiceService.getAllPlanBySn(sn);
                req.setAttribute("allPlanBySn", allPlanBySn);

                //获取sla信息
                List<Map<String, Object>> slaList1 = cbsServiceService.getAllSLABySn(sn);
                String supplement = "";
                if (slaList1.size() > 0) {
                    supplement = (String) slaList1.get(0).get("supplement");
                    if (StringUtil.isNotEmpty(supplement)) {
                        String[] suppmentSplit = supplement.split(",");
                        StringBuffer stringBuffer = new StringBuffer();
                        for (int i = 0; i < suppmentSplit.length; i++) {
                            if (!" ".equals(suppmentSplit[i])) {
                                stringBuffer.append(suppmentSplit[i] + ",");
                            }
                        }
                        if (stringBuffer.toString().length() > 1) {
                            slaList1.get(0).put("supplement", stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1));
                        } else if (stringBuffer.toString().length() == 1) {
                            slaList1.get(0).put("supplement", stringBuffer.toString());
                        } else {
                            slaList1.get(0).put("supplement", null);
                        }
                    }
                    req.setAttribute("slaList1", slaList1.get(0));
                }
            }


            //文件管理
            List<Map<String, Object>> zyFileLogEntityA = cbsServiceAssignListService.getFileLogByServiceId(id, "A");
            List<Map<String, Object>> zyFileLogEntityB = cbsServiceAssignListService.getFileLogByServiceId(id, "B");
            req.setAttribute("zyFileLogEntityA", zyFileLogEntityA.size() != 0 ? zyFileLogEntityA : null);
            req.setAttribute("zyFileLogEntityB", zyFileLogEntityB.size() != 0 ? zyFileLogEntityB : null);

            //文件上传日志管理
            List<Map<String, Object>> zyFileLogList = cbsServiceLogServiceI.getAllFileByCbsId(id);
            req.setAttribute("zyFileLogList", zyFileLogList);

            //查询
//            List<Map<String, Object>> list = systemService.findForJdbc("SELECT u.realname,cbslog.create_date,cbslog.description,filelog.old_file_name FROM cbs_service AS s,zy_file_log AS filelog,t_s_base_user AS u,cbs_service_log AS cbslog WHERE s.person_liable = u.id AND s.id = filelog.business_key AND cbslog.cbs_service_id = s.id AND cbslog.zy_file_log_id = filelog.id AND s.id = '" + id + "'");
//            req.setAttribute("list", list);
            //查询转派处理描述
            List<CbsHandleLogEntity> cbsHandleLogEntityList = systemService.findHql("from CbsHandleLogEntity where businessId='" + id + "' and logType=3 order by createDate DESC");
            req.setAttribute("cbsHandleLogEntityList", cbsHandleLogEntityList);
            /*获取服务处理日志*/
            List<Map<String, Object>> cbsServiceLogList = cbsServiceLogServiceI.getServiceLog(id);
            req.setAttribute("cbsServiceLogList", cbsServiceLogList);

            //获取关联的父子单
            if (code.split("-").length > 0) {
                code = code.split("-")[0];
            }
            List<CbsServiceEntity> cbsServiceEntityList = systemService.findHql("FROM CbsServiceEntity where code like '%" + code + "%'");
            req.setAttribute("cbsServiceEntityList", cbsServiceEntityList); //关联的父子单


            List<Map<String, Object>> cbsServiceEntities = systemService.findForJdbc("SELECT zy_cinema_id AS zycinemaid, zy_equipment_spare_id AS zyequipmentspareid, person_liable AS personliable, close_user AS closeuser, `status` AS `status`,create_name AS createname FROM cbs_service where id= '" + id + "'");
            for (Map<String, Object> cbsServiceEntity : cbsServiceEntities) {
                req.setAttribute("cbsStatus", StringUtil.isNotEmpty(cbsServiceEntity.get("status")) ? cbsServiceEntity.get("status").toString() : "");
                //附加任务信息
                List<CbsServiceTaskMapEntity> cbsServiceTaskMap = cbsServiceTaskMapServiceI.findByProperty(CbsServiceTaskMapEntity.class, "serviceId.id", id);
                req.setAttribute("attachTaskByCondition", cbsServiceTaskMap);

                if (null != cbsServiceEntity.get("personliable") && cbsServiceEntity.get("personliable") != "" && StringUtil.isNotEmpty(cbsServiceEntity.get("personliable").toString())) {
                    TSUser personLiable = systemService.get(TSUser.class, cbsServiceEntity.get("personliable").toString());
                    String realName = personLiable.getRealName();
                    String userName = personLiable.getId();
                    req.setAttribute("personLiable", realName);
                    req.setAttribute("personId", userName);
                }
                if (StringUtil.isNotEmpty(cbsServiceEntity.get("createname"))) {
                    req.setAttribute("createname", cbsServiceEntity.get("createname"));
                }
                if (StringUtil.isNotEmpty(cbsServiceEntity.get("closeuser"))) {
                    TSUser closeUser = systemService.get(TSUser.class, cbsServiceEntity.get("closeuser").toString());
                    String realName1 = closeUser.getRealName();
                    req.setAttribute("closeUser", realName1);
                }
            }
            List<TSDepart> tsDeparts = systemService.findHql("from TSDepart where orgType = ?", StaticValue.DIC_ORG_TYPE_THIRD_PARTY);
            req.setAttribute("tsDeparts", tsDeparts);


            //获取到货异常
            List<ArrivalofabnormalEntity> arrivalOfAbnormal = systemService.findByProperty(ArrivalofabnormalEntity.class, "serviceId.id", id);

            for (ArrivalofabnormalEntity arrivalofabnormalEntity : arrivalOfAbnormal) {
                String sql = "SELECT id, old_file_name, file_path FROM zy_file_log l WHERE l.business_type = 'g' AND business_key = '" + arrivalofabnormalEntity.getId() + "'";
                List<Map<String, Object>> zyFileLogEntities = systemService.findForJdbc(sql);
                arrivalofabnormalEntity.setZyFileLogEntityList(zyFileLogEntities);
            }
            req.setAttribute("arrivalOfAbnormal", arrivalOfAbnormal);

            //获取故障代码
            List<TSTerritory> territoryList = systemService.findHql("from TSTerritory where territoryLevel = 1 order by territorySort");
            req.setAttribute("territoryList", territoryList);
            List<CbsServiceTypeEntity> serviceTypeList = systemService.findHql("from CbsServiceTypeEntity where type = 0 ");
            req.setAttribute("serviceTypeList", serviceTypeList);
            List<CbsErrorTypeEntity> errorTypeList = systemService.findHql("from CbsErrorTypeEntity where type = 0 ");
            req.setAttribute("errorTypeList", errorTypeList);
            List<CbsEquipmentErrorTypeEntity> equipmentErrorTypeList = systemService.findHql("from CbsEquipmentErrorTypeEntity where type = 0 ");
            req.setAttribute("equipmentErrorTypeList", equipmentErrorTypeList);

            req.getSession().setAttribute("cbsId", id);

        }

        return new ModelAndView("com/zybk/cbsservice/cbsService-update-CSA");
    }

    /**
     * @Author X On 2018/9/26 16:17
     * @Description 检查是否可以编辑完工单
     * @params 完工单id
     */
    @ResponseBody
    @RequestMapping(params = "checkForEditServiceReport")
    public AjaxJson checkForEditServiceReport(String serviceId) {
        return cbsServiceService.checkForEditServiceReport(serviceId);
    }

    //查询转派业务的日志信息
    @ResponseBody
    @RequestMapping(params = "toSendLog")
    public AjaxJson toSendLog(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            String id = request.getParameter("id");
            //查询转派处理描述
            List<CbsHandleLogEntity> cbsHandleLogEntityList = systemService.findHql("from CbsHandleLogEntity where businessId='" + id + "' and logType=3  order by createDate DESC");
            if (cbsHandleLogEntityList != null) {
                for (int i = 0; i < cbsHandleLogEntityList.size(); i++) {
                    if (cbsHandleLogEntityList.get(i).getZyFileLogId() != null) {
                        cbsHandleLogEntityList.get(i).setFileName(cbsHandleLogEntityList.get(i).getZyFileLogId().getOldFileName());
                    }
                }
                ajaxJson.setObj(cbsHandleLogEntityList);
            } else {
                ajaxJson.setObj(null);
            }
        } catch (Exception e) {
            e.getMessage();
        }

        return ajaxJson;
    }

    /**
     * 根据选择的服务类型2查询服务类型1
     *
     * @param id 所选省
     * @return
     */
    @RequestMapping(params = "getServiceType2")
    @ResponseBody
    public List<CbsServiceTypeEntity> getServiceType2(String id) {
        return systemService.findHql("from CbsServiceTypeEntity where parentId.id = ? and type = 1 ", id);
    }

    /**
     * 根据选择的服务类型2查询服务类型1
     *
     * @param id 所选省
     * @return
     */
    @RequestMapping(params = "getErrorType2")
    @ResponseBody
    public List<CbsErrorTypeEntity> getErrorType2(String id) {
        return systemService.findHql("from CbsErrorTypeEntity where parentId.id = ? and type = 1 ", id);
    }

    /**
     * 根据选择的服务类型2查询服务类型1
     *
     * @param id 所选省
     * @return
     */
    @RequestMapping(params = "getEquipmentErrorType2")
    @ResponseBody
    public List<CbsEquipmentErrorTypeEntity> getEquipmentErrorType2(String id) {
        return systemService.findHql("from CbsEquipmentErrorTypeEntity where parentId.id = ? and type = 1 ", id);
    }


    @ResponseBody
    @RequestMapping(params = "getPerson")
    public AjaxJson getPerson(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
//        message = "查询成功";
        try {
            TSDepart tsDepart = systemService.singleResult("from TSDepart where departname = '中影巴可（北京）电子有限公司'");
            List<Map<String, Object>> forJdbc = systemService.findForJdbc("SELECT b.id,b.realname from t_s_base_user as b where id in (select org.user_id from t_s_user_org as org where org.org_id = '" + tsDepart.getId() + "') and b.`status` = 1");
            ajaxJson.setObj(forJdbc);
        } catch (Exception e) {
            e.getMessage();
        }
        return ajaxJson;
    }

    @ResponseBody
    @RequestMapping(params = "append")
    public AjaxJson Append(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        message = "追加成功";
        try {
            String cbserviceId = req.getParameter("cbserviceId");
            String personLian = req.getParameter("personLian");
            String descption = req.getParameter("descption");
            //文件id
            String person = req.getParameter("person");
            CbsServiceEntity cbsServiceEntity = new CbsServiceEntity();
            cbsServiceEntity.setId(cbserviceId);

//            5、23 根据新逻辑修改后，注释该内容
//            if (StringUtil.isNotEmpty(descption)) { //    18/5/22 修改，追加描述放到HD处理过程中
//                cbsServiceEntity.setHandleDes(cbsServiceEntity.getHandleDes() + ";" + descption);
//                systemService.saveOrUpdate(cbsServiceEntity);
//            }

            CbsServiceLogEntity cbsServiceLogEntity = new CbsServiceLogEntity();
            ZyFileLogEntity zyFileLogEntity = new ZyFileLogEntity();
            ZyFileLogEntity zyFileLogEntity2 = new ZyFileLogEntity();
            CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();

            if (null != person) {
                zyFileLogEntity.setId(person);
                cbsServiceLogEntity.setZyFileLogId(zyFileLogEntity);
                zyFileLogEntity2.setId(person);
                ZyFileLogEntity o = systemService.singleResult("from ZyFileLogEntity where id='" + person + "'");
                cbsHandleLogEntity.setFileName(o.getOldFileName());
            }
//            cbsHandleLogEntity.setCreateName(personLian);  18/5/18 注释，修改创建人为操作人
            cbsHandleLogEntity.setBusinessId(cbserviceId);
            cbsHandleLogEntity.setDescription(descption);
            cbsHandleLogEntity.setLogType(3);
            if (null != person) {
                cbsHandleLogEntity.setZyFileLogId(zyFileLogEntity2);
            }
            cbsHandleLogServiceI.save(cbsHandleLogEntity);
            cbsServiceLogEntity.setDescription(descption);
            cbsServiceLogEntity.setCbsServiceId(cbsServiceEntity);
            cbsServiceLogServiceI.save(cbsServiceLogEntity);
        } catch (Exception e) {
            message = "追加失败";
        }
        ajaxJson.setMsg(message);
        TSUser user = ResourceUtil.getSessionUserName();
        ajaxJson.setObj(user.getRealName());
        return ajaxJson;
    }

    /**
     * 查看服务单详情页面
     *
     * @return
     */
    @RequestMapping(params = "detail")
    public ModelAndView detail(HttpServletRequest req) {

        String id = req.getParameter("id");
        String sn = req.getParameter("sn");
        String code = req.getParameter("code");
        req.setAttribute("cbsCode", code);

        if (StringUtil.isNotEmpty(id)) {
            /*获取编辑页面基本信息*/
            List<Map<String, Object>> mapList = cbsServiceService.getCbsServiceByCid(id);
            req.setAttribute("mapList", mapList.get(0));

            if (StringUtil.isEmpty(sn)) {
                sn = StringUtil.isNotEmpty(mapList.get(0).get("sn")) ? mapList.get(0).get("sn").toString() : "";
            }
            if (StringUtil.isEmpty(code)) {
                code = StringUtil.isNotEmpty(mapList.get(0).get("code")) ? mapList.get(0).get("code").toString() : "";
            }

            //获取申请的备件
            List<Map<String, Object>> cbsEquipmentApplyEntities = systemService.findForJdbc("SELECT a.id AS id, a.record_id AS code, GROUP_CONCAT(ad.type_des SEPARATOR '\\\\') AS typedes, GROUP_CONCAT(ad.item SEPARATOR '\\\\') AS item, GROUP_CONCAT(ad.total SEPARATOR '\\\\') AS total, a.apply_reason AS reason,a.`status` as `status1`,CASE a.`status` WHEN '1' THEN '待审批' WHEN '2' THEN '审批已通过' WHEN '3' THEN '审批未通过' END `status` FROM CBS_EQUIPMENT_APPLY a LEFT JOIN cbs_equipment_apply_detail ad ON ad.APPLY_ID = a.id WHERE a.service_id ='" + id + "'  GROUP BY record_id");
            if (cbsEquipmentApplyEntities.size() > 0) {
                for (Map<String, Object> cbsEquipmentApplyEntity : cbsEquipmentApplyEntities) {
                    String cbsEq = cbsEquipmentApplyEntity.get("id").toString();
                    String sql = "SELECT e.id, CASE d.`status` WHEN '1' THEN 'CSA待发货' WHEN '2' THEN 'CSA已发货' WHEN '3' THEN 'CSA取消发货' WHEN '4' THEN '欠货中' WHEN '5' THEN '物流待发货' WHEN '6' THEN '物流已发货' WHEN '7' THEN '签收' END AS `status`, IFNULL( DATE_FORMAT( d.expecttime, '%Y-%m-%d  %H:%i:%s' ), '' ) AS expecttime, IFNULL( DATE_FORMAT( d.gettime, '%Y-%m-%d  %H:%i:%s' ), '' ) AS gettime, d.`code` AS `code`, t.type_desc AS typedes, m.item AS item, IFNULL(d.deliver_logistics, '') AS deliverlogistics, IFNULL( DATE_FORMAT( d.LOGISTICS_SENDTIME, '%Y-%m-%d  %H:%i:%s' ), '' ) AS LOGISTICSSENDTIME FROM cbs_deliver_equipment e LEFT JOIN cbs_deliver d ON e.deliver_id = d.id LEFT JOIN cbs_equipment_apply a ON a.id = d.equipment_apply_id LEFT JOIN zy_equipment_type t ON t.id = e.type_id LEFT JOIN zy_es_item m ON m.id = e.item_id WHERE a.id  = '" + cbsEq + "'";
                    List<Map<String, Object>> deliverEquipmentList = systemService.findForJdbc(sql);
                    cbsEquipmentApplyEntity.put("cbsDeliverEquipmentEntities", deliverEquipmentList);
                }

            }
            req.setAttribute("cbsEquipmentApplyEntities", cbsEquipmentApplyEntities);

            if (StringUtil.isNotEmpty(sn)) {
                //服务单历史
                List<Map<String, Object>> serviceBySn = cbsServiceService.getAllServiceBySn(sn);
                req.setAttribute("serviceBySn", serviceBySn);

                //获取影院相关历史
                List<Map<String, Object>> cinemaMapList = cbsServiceService.getCinemaList(sn);
                req.setAttribute("cinemaMapList", cinemaMapList);

                //巡检历史
                List<Map<String, Object>> allPlanBySn = cbsServiceService.getAllPlanBySn(sn);
                req.setAttribute("allPlanBySn", allPlanBySn);

                //获取sla信息
                List<Map<String, Object>> slaList1 = cbsServiceService.getAllSLABySn(sn);
                String supplement = "";
                if (slaList1.size() > 0) {
                    supplement = (String) slaList1.get(0).get("supplement");
                    if (StringUtil.isNotEmpty(supplement)) {
                        String[] suppmentSplit = supplement.split(",");
                        StringBuffer stringBuffer = new StringBuffer();
                        for (int i = 0; i < suppmentSplit.length; i++) {
                            if (!" ".equals(suppmentSplit[i])) {
                                stringBuffer.append(suppmentSplit[i] + ",");
                            }
                        }
                        if (stringBuffer.toString().length() > 1) {
                            slaList1.get(0).put("supplement", stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1));
                        } else if (stringBuffer.toString().length() == 1) {
                            slaList1.get(0).put("supplement", stringBuffer.toString());
                        } else {
                            slaList1.get(0).put("supplement", null);
                        }
                    }
                    req.setAttribute("slaList1", slaList1.get(0));
                }
            }


            //文件管理
            List<Map<String, Object>> zyFileLogEntityA = cbsServiceAssignListService.getFileLogByServiceId(id, "A");
            List<Map<String, Object>> zyFileLogEntityB = cbsServiceAssignListService.getFileLogByServiceId(id, "B");
            req.setAttribute("zyFileLogEntityA", zyFileLogEntityA.size() != 0 ? zyFileLogEntityA : null);
            req.setAttribute("zyFileLogEntityB", zyFileLogEntityB.size() != 0 ? zyFileLogEntityB : null);

            //文件上传日志管理
            List<Map<String, Object>> zyFileLogList = cbsServiceLogServiceI.getAllFileByCbsId(id);
            req.setAttribute("zyFileLogList", zyFileLogList);

            //查询
//            List<Map<String, Object>> list = systemService.findForJdbc("SELECT u.realname,cbslog.create_date,cbslog.description,filelog.old_file_name FROM cbs_service AS s,zy_file_log AS filelog,t_s_base_user AS u,cbs_service_log AS cbslog WHERE s.person_liable = u.id AND s.id = filelog.business_key AND cbslog.cbs_service_id = s.id AND cbslog.zy_file_log_id = filelog.id AND s.id = '" + id + "'");
//            req.setAttribute("list", list);
            //查询转派处理描述
            List<CbsHandleLogEntity> cbsHandleLogEntityList = systemService.findHql("from CbsHandleLogEntity where businessId='" + id + "' and logType=3 order by createDate DESC");
            req.setAttribute("cbsHandleLogEntityList", cbsHandleLogEntityList);
            /*获取服务处理日志*/
            List<Map<String, Object>> cbsServiceLogList = cbsServiceLogServiceI.getServiceLog(id);
            req.setAttribute("cbsServiceLogList", cbsServiceLogList);

            //获取关联的父子单
            if (code.split("-").length > 0) {
                code = code.split("-")[0];
            }
            List<CbsServiceEntity> cbsServiceEntityList = systemService.findHql("FROM CbsServiceEntity where code like '%" + code + "%'");
            req.setAttribute("cbsServiceEntityList", cbsServiceEntityList); //关联的父子单


            List<Map<String, Object>> cbsServiceEntities = systemService.findForJdbc("SELECT zy_cinema_id AS zycinemaid, zy_equipment_spare_id AS zyequipmentspareid, person_liable AS personliable, close_user AS closeuser, `status` AS `status`,CREATE_NAME as createname FROM cbs_service WHERE id= '" + id + "'");
            for (Map<String, Object> cbsServiceEntity : cbsServiceEntities) {
                req.setAttribute("cbsStatus", StringUtil.isNotEmpty(cbsServiceEntity.get("status")) ? cbsServiceEntity.get("status").toString() : "");
                //附加任务信息
                List<CbsServiceTaskMapEntity> cbsServiceTaskMap = cbsServiceTaskMapServiceI.findByProperty(CbsServiceTaskMapEntity.class, "serviceId.id", id);
                req.setAttribute("attachTaskByCondition", cbsServiceTaskMap);

                if (null != cbsServiceEntity.get("personliable") && cbsServiceEntity.get("personliable") != "" && StringUtil.isNotEmpty(cbsServiceEntity.get("personliable").toString())) {
                    TSUser personLiable = systemService.get(TSUser.class, cbsServiceEntity.get("personliable").toString());
                    String realName = personLiable.getRealName();
                    String userName = personLiable.getId();
                    req.setAttribute("personLiable", realName);
                    req.setAttribute("personId", userName);
                }
                if (StringUtil.isNotEmpty(cbsServiceEntity.get("createname"))) {
                    req.setAttribute("createname", cbsServiceEntity.get("createname"));
                }
                if (StringUtil.isNotEmpty(cbsServiceEntity.get("closeuser"))) {
                    TSUser closeUser = systemService.get(TSUser.class, cbsServiceEntity.get("closeuser").toString());
                    String realName1 = closeUser.getRealName();
                    req.setAttribute("closeUser", realName1);

                }
            }
            List<TSDepart> tsDeparts = systemService.findHql("from TSDepart where orgType = ?", StaticValue.DIC_ORG_TYPE_THIRD_PARTY);
            req.setAttribute("tsDeparts", tsDeparts);


            //获取到货异常
            List<ArrivalofabnormalEntity> arrivalOfAbnormal = systemService.findByProperty(ArrivalofabnormalEntity.class, "serviceId.id", id);

            for (ArrivalofabnormalEntity arrivalofabnormalEntity : arrivalOfAbnormal) {
                String sql = "SELECT id, old_file_name, file_path FROM zy_file_log l WHERE l.business_type = 'g' AND business_key = '" + arrivalofabnormalEntity.getId() + "'";
                List<Map<String, Object>> zyFileLogEntities = systemService.findForJdbc(sql);
                arrivalofabnormalEntity.setZyFileLogEntityList(zyFileLogEntities);
            }
            req.setAttribute("arrivalOfAbnormal", arrivalOfAbnormal);

            //获取故障代码
            List<TSTerritory> territoryList = systemService.findHql("from TSTerritory where territoryLevel = 1 order by territorySort");
            req.setAttribute("territoryList", territoryList);
            List<CbsServiceTypeEntity> serviceTypeList = systemService.findHql("from CbsServiceTypeEntity where type = 0 ");
            req.setAttribute("serviceTypeList", serviceTypeList);
            List<CbsErrorTypeEntity> errorTypeList = systemService.findHql("from CbsErrorTypeEntity where type = 0 ");
            req.setAttribute("errorTypeList", errorTypeList);
            List<CbsEquipmentErrorTypeEntity> equipmentErrorTypeList = systemService.findHql("from CbsEquipmentErrorTypeEntity where type = 0 ");
            req.setAttribute("equipmentErrorTypeList", equipmentErrorTypeList);

            req.getSession().setAttribute("cbsId", id);

        }

        return new ModelAndView("com/zybk/cbsservice/cbsService-view");
    }

    @RequestMapping(params = "goPD")
    public ModelAndView goPD(HttpServletRequest request) {
        return new ModelAndView("com/zybk/cbsservice/SendPD");
    }

    /**
     * 进入备份申请页面
     *
     * @return
     */
    @RequestMapping(params = "goSparepartApply")
    public ModelAndView goSparepartApply(HttpServletRequest req) {
        String id = req.getParameter("id");
        String type = req.getParameter("type");
        if (id != null) {
            //获取登录的用户信息
            TSUser user = ResourceUtil.getSessionUserName();
            //用户的角色集合
            List<String> roleList = new ArrayList<>();
            List<TSRoleUser> tsRoleUserList = systemService.findHql("from TSRoleUser where TSUser.id='" + user.getId() + "'");
            for (TSRoleUser tsRoleUser : tsRoleUserList) {
                String role = tsRoleUser.getTSRole().getRoleCode();
                roleList.add(role);
            }
            CbsServiceEntity cbsService = cbsServiceService.getEntity(CbsServiceEntity.class, id);
            if (roleList.contains("barcoHelpdesk") && !"3".equals(cbsService.getStatus())) {
                req.setAttribute("code", 1);
            }
            List<TSTerritory> tSTerritoryHql = systemService.findHql("from TSTerritory where territoryLevel='1'");
            List<TSTerritory> hql = systemService.findHql("from TSTerritory where territoryLevel='2'");
            List<TSType> TSTypeList = systemService.findHql("from TSType where TSTypegroup.typegroupname='申请理由'");
            List<String> idList = systemService.findListbySql("select id from zy_es_item where item='R765952'");
            //List<String> listbySql = systemService.findListbySql("select id from zy_equipment_type where type_desc='LPS'");
            if (idList != null) {
                req.setAttribute("idList", idList.get(0));
            }
            /*if (listbySql != null) {
                req.setAttribute("listbySql", listbySql.get(0));
            }*/
            req.setAttribute("TSTypeList", TSTypeList);
            req.setAttribute("hql", hql);
            req.setAttribute("tSTerritoryHql", tSTerritoryHql);
            req.setAttribute("cbsService", cbsService);
            req.setAttribute("type", type);
        }
        return new ModelAndView("com/zybk/cbsservice/sparepartApply");
    }

    /**
     * 服务单进入报价页面
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "offer")
    public ModelAndView offer(HttpServletRequest req) {
        req.setAttribute("cbsServiceId", req.getParameter("id"));
        return new ModelAndView("com/zybk/cbsservice/cbsServiceOffer");
    }

    /**
     * 取消
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "cancel")
    public ModelAndView cancel(HttpServletRequest req) {
        String id = req.getParameter("id");
        if (id != null) {
            CbsServiceEntity cbsService = cbsServiceService.getEntity(CbsServiceEntity.class, id);
            req.setAttribute("cbsService", cbsService);
        }
        return new ModelAndView("com/zybk/cbsservice/cbsServiceCancel");
    }

    /**
     * 提交取消操作
     *
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "subCancelInfo")
    public AjaxJson subCancelInfo(HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        String id = req.getParameter("id");
        String remark = req.getParameter("remark");
        if (id != null) {
            CbsServiceEntity cbsService = cbsServiceService.getEntity(CbsServiceEntity.class, id);
            if (StringUtil.isNotEmpty(cbsService) && !cbsService.getStatus().equals(StaticValue.yqx)) {
                SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
                String serviceType = "";
                if (StringUtil.isNotEmpty(cbsService.getServiceType2())) {
                    serviceType = cbsService.getServiceType2().getName();
                }
                String code = cbsService.getCode();
                String zyCinemaName = cbsService.getZyCinemaName();
                TSUser user = ResourceUtil.getSessionUserName();
                String level = cbsService.getLevel();
                String type = "";
                if (StringUtil.isNotEmpty(cbsService.getZyEquipmentSpareServiceId())) {
                    type = cbsService.getZyEquipmentSpareServiceId().getType().getTypeDesc();
                } else if (StringUtil.isNotEmpty(cbsService.getZyEquipmentSpareId())) {
                    type = cbsService.getZyEquipmentSpareId().getType().getTypeDesc();
                }

                List<CbsDelinerEntity> cbsDeliners = systemService.findByProperty(CbsDelinerEntity.class, "crCode", cbsService.getCode());
                if (cbsDeliners.size() > 0) {
                    for (CbsDelinerEntity cbsDeliner : cbsDeliners) {
                        if (cbsDeliner.getStatus().equals(StaticValue.wldfh) || cbsDeliner.getStatus().equals(StaticValue.wlyfh) || cbsDeliner.getStatus().equals(StaticValue.qs)) {
//                            flag = false;   //18/5/18修改为，无论发货单是否能取消，发货单都能取消

                            //邮件通知值班CSA进行处理，含有不能取消的发货单
                            List<TSRoleUser> tsRoleUserList = systemService.findHql("from TSRoleUser where TSRole.roleCode='" + StaticValue.RULE_CODE_BARCO_CSA_ZB + "'");
                            for (TSRoleUser tsRoleUser : tsRoleUserList) {
                                if (tsRoleUser.getTSUser().getStatus().equals(Globals.User_Normal)) {  //值班CSA状态是正常的情况
                                    ZyEmailEntity eMail = new ZyEmailEntity();

                                    String s = "巴可服务单取消，请处理相关发货：<" + level + ">-<" + serviceType + ">-<" + code + ">-<" + zyCinemaName + ">-" + sdf.format(new Date()) + "";
                                    eMail.setEmailSubject(s);
                                    eMail.setEmailReceiver(tsRoleUser.getTSUser().getEmail());
                                    Map<String, Object> paraMap1 = new HashMap<String, Object>();
                                    paraMap1.put("code", code);
                                    paraMap1.put("remark", remark);
                                    paraMap1.put("cbsDelinerCode", cbsDeliner.getCode());
                                    paraMap1.put("name", user.getRealName());
                                    paraMap1.put("phone", user.getMobilePhone());
                                    if (StringUtil.isNotEmpty(tsRoleUser.getTSUser().getEmail())) {
                                        SendMailUtil.sendFtlMail(eMail, "mail_qx_service_business.ftl", paraMap1, systemService);
                                    }
                                }
                            }
                        }

                        /*可以取消发货时，发送消息*/
                        if (cbsDeliner.getStatus().equals(StaticValue.CSAdfh) || cbsDeliner.getStatus().equals(StaticValue.qh)) {
                            cbsDeliner.setStatus(StaticValue.CSAqx);
                            cbsDeliner.setOffReason("取消服务单导致发货单取消");
                            cbsDeliner.setQxUser(user);
                            systemService.saveOrUpdate(cbsDeliner);
                            //添加发货单操作日志
                            cbsDelinerService.addDeliverLog(user.getRealName() + "创建了发货单", cbsDeliner.getId(), 1);

                            //取消发货单，发送短信和邮件通知（备件申请人和备件审批人）
                            String emailTitle = "发货单取消：<" + level + ">-<" + serviceType + ">-<" + code + ">-<" + zyCinemaName + ">-" + sdf.format(new Date());
                            //邮件通知审批人
                            cbsDelinerService.sendMail(cbsDeliner, user, "sp", emailTitle, "mail_deliver_CSAQx.ftl");
                            //邮件和短信、app通知申请人
                            cbsDelinerService.sendMail(cbsDeliner, user, "sq", emailTitle, "mail_deliver_CSAQx.ftl");
                            cbsDelinerService.sendMsg(cbsDeliner, user, "sq", "message_deliver_CSAQx.ftl");

                            /*APP消息*/
                            if (cbsDeliner != null) {
                                CbsEquipmentApplyEntity apply = cbsDeliner.getEquipmentApplyId();
                                if (apply != null) {
                                    if (StringUtil.isNotEmpty(apply.getCreateBy())) { //备件申请人
                                        TSUser applyUser = systemService.singleResult("from TSUser where userName='" + apply.getCreateBy() + "'");
                                        if (applyUser != null) {
                                            CbsAppMessageEntity appMessage = new CbsAppMessageEntity();
                                            String content = "您的发货<" + cbsDeliner.getCode() + ">已取消，取消原因:<" + cbsDeliner.getOffReason() + ">。如有疑问请联系处理人：<" + user.getRealName() + "> <" + user.getMobilePhone() + ">。";
                                            appMessage.setContent(content);
                                            appMessage.setSender(user.getId());
                                            appMessage.setReciver(applyUser.getId());
                                            appMessage.setState(StaticValue.DIC_APP_MESSAGE_STATE_UNREAD);
                                            systemService.save(appMessage);
                                            systemService.addLog("新增APP消息,接受方:" + applyUser.getId() + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    //服务单日志
                    cbsServiceLogServiceI.addServiceLog(cbsService, StaticValue.Close_Service_Log_Type_2, "因服务单取消,相关的发货单已自动取消，原因:" + (StringUtil.isNotEmpty(remark) ? remark : ""), null);

                } else {
                    //服务单日志
                    cbsServiceLogServiceI.addServiceLog(cbsService, StaticValue.Close_Service_Log_Type_2, "服务单取消,原因:" + (StringUtil.isNotEmpty(remark) ? remark : ""), null);

                }

                //取消服务单发送消息
                if (StringUtil.isNotEmpty(cbsService.getZyContacts())) {
                    ZyContactsEntity zyContacter = systemService.getEntity(ZyContactsEntity.class, cbsService.getZyContacts());
                    //服务商维修商务 邮件
                    ZyEmailEntity eMail = new ZyEmailEntity();

                    String s = "巴可服务单取消：<" + level + ">-<" + serviceType + ">-<" + code + ">-<" + zyCinemaName + ">-" + sdf.format(new Date()) + "";
                    eMail.setEmailSubject(s);
                    eMail.setEmailReceiver(zyContacter.getEmail());
                    Map<String, Object> paraMap1 = new HashMap<String, Object>();
                    paraMap1.put("contacterName", zyContacter.getBelongOrg().getShortname());
                    paraMap1.put("code", code);
                    paraMap1.put("remark", remark);
                    paraMap1.put("name", user.getRealName());
                    paraMap1.put("phone", user.getMobilePhone());
                    if (StringUtil.isNotEmpty(zyContacter.getEmail())) {
                        SendMailUtil.sendFtlMail(eMail, "mail_qx_service.ftl", paraMap1, systemService);
                    }
                    /*短信*/
                    Map<String, Object> paraMap = new HashMap<String, Object>();
                    paraMap.put("code", code);
                    SendMessage.sendSMSFTL(zyContacter.getCellphone1(), "message_qx_service_business.ftl", paraMap, systemService);

                    /*APP消息*/
                    CbsAppMessageEntity appMessage = new CbsAppMessageEntity();
                    String content = "您的服务单" + code + "已取消，取消原因:" + remark + "。如有疑问请联系处理人：" + user.getRealName() + " " + user.getMobilePhone() + "。";
                    appMessage.setContent(content);
                    appMessage.setSender(user.getId());
                    TSBaseUser baseUser = systemService.get(TSBaseUser.class, zyContacter.getTsBaseUser().getId());
                    appMessage.setReciver(baseUser.getId());
                    appMessage.setState(StaticValue.DIC_APP_MESSAGE_STATE_UNREAD);
                    systemService.save(appMessage);
                    systemService.addLog("新增APP消息,接受方:" + baseUser.getId() + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);

                    //当前处理工程师
                    if (StringUtil.isNotEmpty(cbsService.getEngineer())) {
                        ZyEngineerEntity zyEngineerEntity = systemService.getEntity(ZyEngineerEntity.class, cbsService.getEngineer());
                        ZyEmailEntity eMail1 = new ZyEmailEntity();
                        eMail1.setEmailSubject(s);
                        eMail1.setEmailReceiver(zyEngineerEntity.getEmail());
                        if (StringUtil.isNotEmpty(zyEngineerEntity.getEmail())) {
                            SendMailUtil.sendFtlMail(eMail1, "mail_qx_service.ftl", paraMap1, systemService);
                        }
                        SendMessage.sendSMSFTL(zyEngineerEntity.getCellphone(), "message_qx_service_business.ftl", paraMap, systemService);

                        /*APP消息*/
                        CbsAppMessageEntity appMessage1 = new CbsAppMessageEntity();
                        appMessage1.setContent(content);
                        appMessage1.setSender(user.getId());
                        TSBaseUser baseUser1 = systemService.get(TSBaseUser.class, zyEngineerEntity.getTsBaseUser().getId());
                        appMessage1.setReciver(baseUser1.getId());
                        appMessage1.setState(StaticValue.DIC_APP_MESSAGE_STATE_UNREAD);
                        systemService.save(appMessage1);
                        systemService.addLog("新增APP消息,接受方:" + baseUser1.getId() + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);

                    }
                }


                cbsService.setStatus(StaticValue.yqx);
                cbsService.setZyContacts("");
                cbsService.setAreaEngineer("");
                cbsService.setEngineer("");
                systemService.saveOrUpdate(cbsService);

                //删除所有的派单信息
                systemService.updateBySqlString("DELETE FROM cbs_service_assign_list WHERE service_id = '" + cbsService.getId() + "'");

                j.setObj(cbsService.getCode());
                j.setMsg("取消成功");
                j.setSuccess(true);
            } else {
                j.setObj(cbsService.getCode());
                j.setMsg("服务单已取消，请刷新服务单");
                j.setSuccess(true);
            }
        }
        return j;
    }

    /**
     * 上传附件功能
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "fileUploadView")
    public AjaxJson fileUploadView(HttpServletRequest request) throws UnsupportedEncodingException {
        AjaxJson j = new AjaxJson();
        Map<String, Object> attributes = new HashMap<String, Object>();
        TSUser tsUser = ResourceUtil.getSessionUserName();
        String cbsServiceId = oConvertUtils.getString(request.getParameter("cbsServiceId"));
        String businessType = request.getParameter("businessType");
        String photoType = request.getParameter("photoType");
        if (photoType != null) {
            photoType = URLDecoder.decode(photoType, "UTF-8");
        }
        if (cbsServiceId != null && cbsServiceId != "") {
            FileBean fileBean = UploadFileUtil.UploadFile(request);
            if (StringUtil.isNotEmpty(cbsServiceId)) {
                ZyFileLogEntity zyfileLog = new ZyFileLogEntity();
                zyfileLog.setBusinessKey(cbsServiceId);
                zyfileLog.setFilePath(fileBean.getSavePath());
                if (photoType != null && photoType != "") {
                    fileBean.setFileRealName(photoType + ".jpg");
                }
                zyfileLog.setOldFileName(fileBean.getFileRealName());
                zyfileLog.setNewFileName(fileBean.getFileName());
                zyfileLog.setCreateDate(new Date());
                zyfileLog.setCreateDate(new Date());
                CbsServiceLogEntity cbsServiceLog = new CbsServiceLogEntity();
                CbsServiceEntity cbsService = systemService.getEntity(CbsServiceEntity.class, cbsServiceId);
                if ("F1".equals(businessType)) {
                    zyfileLog.setBusinessType("F1");
                    zyfileLog.setFileType("wgd");
                    systemService.save(zyfileLog);
                } else if ("F2".equals(businessType)) {
                    zyfileLog.setBusinessType("F2");
                    zyfileLog.setFileType("wgd");
                    systemService.save(zyfileLog);
                } else if ("F".equals(businessType)) {
                    zyfileLog.setBusinessType("F");
                    systemService.save(zyfileLog);
                } else if ("F3".equals(businessType)) {
                    zyfileLog.setBusinessType("F3");
                    zyfileLog.setFileType("wgd");
                    systemService.save(zyfileLog);
                } else if ("F4".equals(businessType)) {
                    zyfileLog.setBusinessType("F4");
                    zyfileLog.setFileType("wgd");
                    systemService.save(zyfileLog);
                } else if ("bjd".equals(businessType)) {
                    zyfileLog.setBusinessType("报价单");
                    systemService.save(zyfileLog);
                    cbsServiceLog.setCbsServiceId(cbsService);
                    cbsServiceLog.setLogType(1);
                    cbsServiceLog.setDescription("上传报价单");
                    List<ZyFileLogEntity> zyFileLoghql = systemService.findHql("from ZyFileLogEntity order by createDate desc");
                    cbsServiceLog.setZyFileLogId(zyFileLoghql.get(0));
                    systemService.save(cbsServiceLog);
                } else if ("G1".equals(businessType)) {
                    zyfileLog.setBusinessType("G1");
                    zyfileLog.setFileType("wgd");
                    systemService.save(zyfileLog);
                } else if ("G2".equals(businessType)) {
                    zyfileLog.setBusinessType("G2");
                    zyfileLog.setFileType("wgd");
                    systemService.save(zyfileLog);
                } else if ("G3".equals(businessType)) {
                    zyfileLog.setBusinessType("G3");
                    zyfileLog.setFileType("wgd");
                    systemService.save(zyfileLog);
                } else if ("H1".equals(businessType)) {
                    zyfileLog.setBusinessType("H1");
                    zyfileLog.setFileType("wgd");
                    systemService.save(zyfileLog);
                } else if ("H2".equals(businessType)) {
                    zyfileLog.setBusinessType("H2");
                    zyfileLog.setFileType("wgd");
                    systemService.save(zyfileLog);
                } else if ("XC1".equals(businessType)) {
                    zyfileLog.setBusinessType("XC1");
                    zyfileLog.setFileType("wgd");
                    systemService.save(zyfileLog);
                } else if ("XC2".equals(businessType)) {
                    zyfileLog.setBusinessType("XC2");
                    zyfileLog.setFileType("wgd");
                    systemService.save(zyfileLog);
                } else if ("XC3".equals(businessType)) {
                    zyfileLog.setBusinessType("XC3");
                    zyfileLog.setFileType("wgd");
                    systemService.save(zyfileLog);
                } else if ("XC4".equals(businessType)) {
                    zyfileLog.setBusinessType("XC4");
                    zyfileLog.setFileType("wgd");
                    systemService.save(zyfileLog);
                } else if ("XC5".equals(businessType)) {
                    zyfileLog.setBusinessType("XC5");
                    zyfileLog.setFileType("wgd");
                    systemService.save(zyfileLog);
                } else if ("XC6".equals(businessType)) {
                    zyfileLog.setBusinessType("XC6");
                    zyfileLog.setFileType("wgd");
                    systemService.save(zyfileLog);
                } else if ("XC7".equals(businessType)) {
                    List<Map<String, Object>> list = systemService.findForJdbc("SELECT id FROM zy_file_log WHERE business_key = ? AND business_type = ?  ORDER BY create_date DESC ", cbsServiceId, businessType);
                    if (list.size() > 0) {
                        String id = list.get(0).get("id").toString();
                        systemService.deleteEntityById(ZyFileLogEntity.class, id);   //删除上一条上传过的克隆包
                    }
                    zyfileLog.setBusinessType("XC7");
                    zyfileLog.setFileType("wgd");
                    systemService.saveOrUpdate(zyfileLog);
                } else {
                    if (cbsService.getPersonLiable() != null) {
                        zyfileLog.setCreateName(cbsService.getPersonLiable().getRealName());
                        zyfileLog.setCreateBy(cbsService.getPersonLiable().getRealName());
                    }
                    systemService.save(zyfileLog);
                }
//                zyfileLog.setBusinessType(StaticValue.FILE_SERVICE_OFFER_TYPE_DATA);
//                zyfileLog.setBusinessChildType("A");
            }
            String id = null;
            Map<String, Object> fileLogMap = systemService.findOneForJdbc("SELECT t.id FROM zy_file_log t where  t.business_key = '" + cbsServiceId + "' and old_file_name = '" + fileBean.getFileRealName() + "'order by t.create_date desc limit 1 ");
            if (fileLogMap != null) {
                id = fileLogMap.get("id").toString();
            }
            attributes.put("name", fileBean.getFileRealName());
            attributes.put("id", id);
            j.setAttributes(attributes);
        }
        return j;
    }

    @ResponseBody
    @RequestMapping(params = "upLoadImg", method = RequestMethod.POST)
    public AjaxJson upLoadImg(@RequestParam("id") String id, @RequestParam MultipartFile file, HttpServletRequest request) throws IOException {
        Map<String, Object> map = new HashMap();
        AjaxJson ajaxJson = new AjaxJson();
        try {
            //文件的实际路径
            String filePath = StaticValue.UPLOAD_PATH;
            File fileDirectory = new File(filePath);
            if (!fileDirectory.exists() && !fileDirectory.isDirectory()) {
                fileDirectory.mkdirs();
            }
            System.out.println("文件名称:" + file.getName());
            System.out.println("文件长度:" + file.getSize());
            System.out.println("文件类型:" + file.getContentType());
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString().replace("-", "") + suffix;//构建文件名称
            String fileRealName = file.getOriginalFilename();
            String uploadPath = filePath + newFileName;
            File file1 = new File(uploadPath);
            file1.createNewFile();
            file.transferTo(file1);
            ZyFileLogEntity zyfileLog = new ZyFileLogEntity();
            zyfileLog.setFilePath(file1.getAbsolutePath());
            zyfileLog.setOldFileName(fileRealName);
            zyfileLog.setNewFileName(newFileName);
            zyfileLog.setBusinessKey(id);
            systemService.save(zyfileLog);
//           map.put("cbserviceId",id);
//           map.put("FileName",newFileName);
//           ajaxJson.setAttributes(map);
            ajaxJson.setObj(zyfileLog);
        } catch (Exception e) {
            message = "上传失败";
        }
        return ajaxJson;
    }

    @ResponseBody
    @RequestMapping(params = "uploadAppHeadFile")
    public AjaxJson uploadAppHeadFile(HttpServletRequest request) {
        String cbsId = (String) request.getSession().getAttribute("cbsId");
        AjaxJson j = new AjaxJson();
        boolean flag = true;
        try {
            MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = req.getFile("Filedata");
            String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            long maxSize = 8 * 1024 * 1024;
            if (multipartFile.getSize() > maxSize) {
                flag = false;
                message = "图片大小超出限制";
            } else {
                TSUser user = ResourceUtil.getSessionUserName();
                String filePath = StaticValue.UPLOAD_PATH;
                File fileDirectory = new File(filePath);
                if (!fileDirectory.exists() && !fileDirectory.isDirectory()) {
                    fileDirectory.mkdirs();
                }
                String newFileName = UUID.randomUUID().toString().replace("-", "") + suffix;//构建文件名称
                String fileRealName = multipartFile.getOriginalFilename();
                String uploadPath = filePath + newFileName;
                File file = new File(uploadPath);
                file.createNewFile();
                multipartFile.transferTo(file);
                ZyFileLogEntity zyfileLog = new ZyFileLogEntity();
                zyfileLog.setFilePath(file.getAbsolutePath());
                zyfileLog.setOldFileName(fileRealName);
                zyfileLog.setNewFileName(newFileName);
                zyfileLog.setBusinessKey(cbsId);
                systemService.save(zyfileLog);
                j.setObj(zyfileLog);
//                user = systemService.getEntity(TSUser.class, user.getId());
//                user.setHeadFileLogId(zyfileLog.getId());
//                systemService.saveOrUpdate(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
            message = "上传失败";
        }
        j.setMsg(message);
        j.setSuccess(flag);
        return j;
    }

    /**
     * 删除上传的文件
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "delFile")
    public AjaxJson delFile(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            String id = oConvertUtils.getString(request.getParameter("id"));
            if (id != null && id != "") {
                systemService.deleteEntityById(ZyFileLogEntity.class, id);
                int i = systemService.updateBySqlString("DELETE FROM cbs_service_log WHERE zy_file_log_id = '" + id + "'");
                j.setMsg("文件删除成功");
                j.setSuccess(true);
            }
        } catch (Exception e) {
            j.setMsg(e.getMessage());
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }

    /**
     * 进入派单页面
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "goDispatchOrder")
    public ModelAndView goDispatchOrder(HttpServletRequest req) {
        String id = req.getParameter("id");
        String serviceProviderCode = req.getParameter("serviceProviderCode");
        String repairProvider = req.getParameter("repairProvider");
        String change = req.getParameter("change");
        String type = req.getParameter("type");
        req.setAttribute("type", type);
        req.setAttribute("serviceProviderCode", serviceProviderCode);
        req.setAttribute("repairProvider", repairProvider);
        if ("changeStatus".equals(change)) {
            changeStatus(id, req);
            req.setAttribute("changeStatus", change);
        }
        String mmobj = "";//服务描述
        if (StringUtil.isNotEmpty(req.getParameter("mmobj")) && !req.getParameter("mmobj").equals("null")) {
            mmobj = req.getParameter("mmobj");
        }
        String equipmentId = "";
        String cinemaId = "";
        if (id != null) {
            List<TSDepart> tsDeparts = systemService.findHql("from TSDepart where orgType = ?", StaticValue.DIC_ORG_TYPE_THIRD_PARTY);
            req.setAttribute("tsDeparts", tsDeparts);
            List<Map<String, Object>> cbsService = systemService.findForJdbc("SELECT s.id, s.handle_des, s.authentication, s.zy_equipment_spare_id, s.zy_cinema_id,s.judge400 as judge400,s.description as description FROM cbs_service s where s.id = ?", id);
            if (StringUtil.isNotEmpty(cbsService)) {
                req.setAttribute("cbsService", cbsService.get(0));

                String judge400 = StringUtil.isNotEmpty(cbsService.get(0).get("judge400")) ? cbsService.get(0).get("judge400").toString() : "";
                String description = StringUtil.isNotEmpty(cbsService.get(0).get("description")) ? cbsService.get(0).get("description").toString() : "";
                if (StringUtil.isNotEmpty(description)) {
                    mmobj += description + ";";
                }
                if (StringUtil.isNotEmpty(judge400)) {
                    mmobj += judge400 + ";";
                }

            }
            Object spareId = cbsService.get(0).get("zy_equipment_spare_id");
            Object zyCinemaId = cbsService.get(0).get("zy_cinema_id");
            List<Map<String, Object>> attachTaskByCondition = null;
            //设备id
            if (StringUtil.isNotEmpty(cbsService.get(0).get("zy_equipment_spare_id")) && StringUtil.isNotEmpty(cbsService.get(0).get("zy_cinema_id"))) {
                //获取设备iD
                equipmentId = cbsService.get(0).get("zy_equipment_spare_id").toString();
                //获取影院id
                cinemaId = cbsService.get(0).get("zy_cinema_id").toString();
                //获取附加任务
                attachTaskByCondition = cbsAttachTaskService.getAttachTaskByConditionByStatus(cinemaId, equipmentId);

                req.setAttribute("attachTaskByCondition", attachTaskByCondition);
            } else if (spareId != null && zyCinemaId == null) {

                //获取设备iD
                equipmentId = cbsService.get(0).get("zy_equipment_spare_id").toString();
                //获取附加任务
                attachTaskByCondition = cbsAttachTaskService.getAttachTaskByConditionByStatus("0", equipmentId);

                req.setAttribute("attachTaskByCondition", attachTaskByCondition);
            } else if (spareId == null && zyCinemaId != null) {
                //获取影院id
                cinemaId = cbsService.get(0).get("zy_cinema_id").toString();
                //获取附加任务
                attachTaskByCondition = cbsAttachTaskService.getAttachTaskByConditionByStatus(cinemaId, "");

                req.setAttribute("attachTaskByCondition", attachTaskByCondition);
            } else {
                //获取附加任务
                attachTaskByCondition = cbsAttachTaskService.getAttachTaskByConditionByStatus(null, null);

                req.setAttribute("attachTaskByCondition", attachTaskByCondition);
            }
            //获取选中的附加任务
            List<CbsServiceTaskMapEntity> cbsServiceTaskMapList = systemService.findByProperty(CbsServiceTaskMapEntity.class, "serviceId.id", id);
            if (attachTaskByCondition != null) {
                for (Map<String, Object> map : attachTaskByCondition) {
                    map.put("isTrue", "0");
                    for (CbsServiceTaskMapEntity cbsServiceTaskMapEntity : cbsServiceTaskMapList) {
                        if (cbsServiceTaskMapEntity.getAttachTaskId().getId().equals(map.get("id"))) {
                            map.put("isTrue", "1");
                        }
                    }
                }
            }
            String sql = "SELECT s.id, s.`code`, CONCAT(t.`name`, '>>', t1.`name`) AS `name`, s.`level` FROM cbs_service s LEFT JOIN cbs_service_type t ON s.service_type_1 = t.id LEFT JOIN cbs_service_type t1 ON s.service_type_2 = t1.id WHERE s.id = '" + id + "'";
            List<Map<String, Object>> list = systemService.findForJdbc(sql);
            //CR号，服务单类型，级别
            if (list.size() > 0) {
                Map map = new HashMap();
                req.setAttribute("code", list.get(0).get("code").toString());
                req.setAttribute("name", StringUtil.isNotEmpty(list.get(0).get("name")) ? list.get(0).get("name").toString() : "");
                req.setAttribute("level", StringUtil.isNotEmpty(list.get(0).get("level")) ? list.get(0).get("level").toString() : "");
            }
        }
        if (StringUtil.isEmpty(mmobj)) {
            mmobj = "";
        }
        req.setAttribute("mmobj", mmobj);
        return new ModelAndView("com/zybk/cbsservice/cbsServiceDispatchOrder");
    }

    /**
     * 进入详情页面
     *
     * @param
     * @return
     */
    @RequestMapping(params = "getDetial")
    public ModelAndView getDetial(HttpServletRequest req) {
        String type = req.getParameter("type");
        String sn = req.getParameter("sn");
        if (StringUtil.isNotEmpty(sn)) {
            if (type.equals("1")) {
                //获取设备服务单记录 CBS_SERVICE
                List<Map<String, Object>> mapList = cbsServiceService.getAllService(sn);
                req.setAttribute("cbsServiceList", mapList);
            }
            if (type.equals("2")) {
                //获取影院服务单记录 CBS_SERVICE
                List<Map<String, Object>> mapList1 = cbsServiceService.getCinemaList(sn);
                req.setAttribute("cbsServiceList1", mapList1);
            }
            if (type.equals("3")) {
                List<Map<String, Object>> zyInspectionPlanList = cbsServiceService.getAllPlanBySn(sn);
                req.setAttribute("zyInspectionPlanList", zyInspectionPlanList);
            }
            if (type.equals("4")) {  /*关联父子单展开*/
                if (sn.split("-").length > 0) {
                    sn = sn.split("-")[0];
                }
                List<CbsServiceEntity> cbsServiceEntityList = systemService.findHql("FROM CbsServiceEntity where code like '%" + sn + "-%'");
                req.setAttribute("cbsServiceEntityList", cbsServiceEntityList); //关联的父子单
            }
            if (type.equals("5")) { /*处理描述展开*/
                List<CbsHandleLogEntity> cbsHandleLogEntityList = systemService.findHql("from CbsHandleLogEntity where businessId='" + sn + "' and logType=3  order by createDate DESC");
                req.setAttribute("cbsHandleLogEntityList", cbsHandleLogEntityList);
            }
        }
        req.setAttribute("type", type);
        return new ModelAndView("com/zybk/cbsservice/getDetial");
    }


    //关单
    @RequestMapping(params = "closeService")
    @ResponseBody
    public AjaxJson closeService(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = request.getParameter("id");  //服务单id
        Map map = new HashMap();
        if (StringUtil.isNotEmpty(id)) {
            CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, id);
            if (StringUtil.isNotEmpty(cbsServiceEntity)) {
                String speedStatus = cbsServiceEntity.getSpeedStatus(); //第三方状态
                String status = cbsServiceEntity.getStatus(); //服务单状态
                if (!status.equals(StaticValue.ywc)) {
                    if (StringUtil.isNotEmpty(cbsServiceEntity.getSpecial()) && cbsServiceEntity.getSpecial() == 1) {
                        String sql = "SELECT COUNT(id) as count from zy_file_log WHERE business_child_type='" + StaticValue.Business_File_Type_B + "' and business_key='" + cbsServiceEntity.getId() + "'";
                        List<Map<String, Object>> i = systemService.findForJdbc(sql);
                        if (i.size() > 0) {
                            Long m = Long.parseLong(i.get(0).get("count").toString());
                            if (m == 0) {
                                ajaxJson.setSuccess(false);
                                ajaxJson.setMsg("特批文件为空，不能关单！");
                            }
                        }
                    }
                    if (speedStatus.equals(StaticValue.fwywc)) {//跳转关单页面，填写关单备注
                        map.put("type", "1");
                    }
                    if (!speedStatus.equals(StaticValue.fwywc)) {//根据不同类型跳转不同完工单页面
                        if (StringUtil.isNotEmpty(cbsServiceEntity.getServiceType1()) && StringUtil.isNotEmpty(cbsServiceEntity.getServiceType2())) {
                            //判断是否有完工单类型，type=2：代表有完工单   type=1：代表没有完工单
                            if ("故障维修".equals(cbsServiceEntity.getServiceType1().getName()) ||
                                    ("服务支持".equals(cbsServiceEntity.getServiceType1().getName()) &&
                                            ("现场检测".equals(cbsServiceEntity.getServiceType2().getName()) ||
                                                    "技术支持".equals(cbsServiceEntity.getServiceType2().getName()) ||
                                                    "维保检测".equals(cbsServiceEntity.getServiceType2().getName()))) ||
                                    ("增值服务".equals(cbsServiceEntity.getServiceType1().getName()) &&
                                            ("引擎翻新".equals(cbsServiceEntity.getServiceType2().getName()) ||
                                                    "光管翻新".equals(cbsServiceEntity.getServiceType2().getName())))) {
                                map.put("type", "2");
                            } else {
                                map.put("type", "1");
                            }
                        } else {
                            map.put("type", "1");
                        }
                    }
                    ajaxJson.setObj(cbsServiceEntity.getCode());
                    ajaxJson.setAttributes(map);
                } else {
                    ajaxJson.setMsg("服务单状态为已完成，不能进行关单。如状态不符，请刷新页面！");
                }
            } else {
                ajaxJson.setMsg("服务单不存在！");
            }
        } else {
            ajaxJson.setMsg("服务单id为空！");
        }
        return ajaxJson;
    }

    @RequestMapping(params = "goSparepartApplyBegin")
    @ResponseBody
    public AjaxJson goSparepartApplyBegin(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = request.getParameter("id");  //服务单id
        boolean flag = true;
        if (StringUtil.isNotEmpty(id)) {
            CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, id);
            if (StringUtil.isNotEmpty(cbsServiceEntity)) {
                if (StringUtil.isNotEmpty(cbsServiceEntity.getSpecial())) {
                    if (flag && 1 == cbsServiceEntity.getSpecial()) {
                        String sql = "SELECT COUNT(id) as count from zy_file_log WHERE business_child_type='" + StaticValue.Business_File_Type_B + "' and business_key='" + cbsServiceEntity.getId() + "'";
                        List<Map<String, Object>> i = systemService.findForJdbc(sql);
                        if (i.size() > 0) {
                            Long m = Long.parseLong(i.get(0).get("count").toString());
                            if (m == 0) {
                                ajaxJson.setSuccess(false);
                                ajaxJson.setMsg("特批文件为空，不能申请备件！");
                                flag = false;
                            }

                        }
                    }
                }
                if (StringUtil.isNotEmpty(cbsServiceEntity.getStatus())) {
                    if (cbsServiceEntity.getStatus().equals(StaticValue.ywc) || cbsServiceEntity.getSpeedStatus().equals(StaticValue.fwywc) || cbsServiceEntity.getStatus().equals(StaticValue.yqx)) {
                        ajaxJson.setSuccess(false);
                        ajaxJson.setMsg("服务单该状态下不能申请备件！");
                        flag = false;
                    }
                }
            }
        }

        return ajaxJson;
    }

    /**
     * 跳转关单页面
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(params = "sureCloseService")
    public ModelAndView sureCloseService(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");  //服务单id
        request.setAttribute("id", id);
        return new ModelAndView("com/zybk/cbsservice/cbsService-close");
    }

    @RequestMapping(params = "cbsServiceOffer")
    @ResponseBody
    public AjaxJson cbsServiceOffer(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        String remark = request.getParameter("remark");
        String cbsServiceId = request.getParameter("cbsServiceId"); //服务单id

        if (StringUtil.isNotEmpty(cbsServiceId)) {
            CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, cbsServiceId);
            cbsServiceEntity.setOfferNo(remark);
            systemService.saveOrUpdate(cbsServiceEntity);
            cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, "服务单进行了报价" + (StringUtil.isNotEmpty(remark) ? (":" + remark) : ""), null);
        }
        systemService.addLog(remark, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        j.setMsg("保存成功！");
        return j;
    }

    /**
     * 关单操作
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(params = "closeServiceList")
    @ResponseBody
    public AjaxJson closeServiceList(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson j = new AjaxJson();
        j = cbsServiceService.closeServiceList(request, response);
        return j;
    }

    /**
     * @param zyEquipmentTypeEntity
     * @param request
     * @param response
     * @param
     * @author xiul
     * 2018-1-22 上午12:00:42
     * Description 设备item - 选择设备类型datagrid加载
     */
    @RequestMapping(params = "dataGridOfChooseEquipmentType")
    @ResponseBody
    public List<TreeGrid> dataGridOfChooseEquipmentType(ZyEquipmentTypeEntity zyEquipmentTypeEntity, HttpServletRequest request, HttpServletResponse response, TreeGrid treegrid) {
        CriteriaQuery cq;
        List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
        cq = new CriteriaQuery(ZyEquipmentTypeEntity.class);
        if (treegrid.getId() != null) {
            cq.eq("equipmentType.id", treegrid.getId());
        } else if (treegrid.getId() == null) {
            cq.isNull("equipmentType.id");
            //cq.eq("equipmentType.id","402883f3545bca4101545bdde56f0004");
        }
        cq.add();
        List<ZyEquipmentTypeEntity> ZyEquipmentTypeList = systemService.getListByCriteriaQuery(cq, false);
        TreeGridModel treeGridModel = new TreeGridModel();
        treeGridModel.setIdField("id");
        treeGridModel.setTextField("typeDesc");
        treeGridModel.setParentId("equipmentType_id");
        treeGridModel.setParentText("equipmentType_typeDesc");
        treeGridModel.setSrc("");
        treeGridModel.setChildList("childEquipmentTypes");
        treeGrids = systemService.treegrid(ZyEquipmentTypeList, treeGridModel);
        return treeGrids;
    }

    /**
     * @param request
     * @return
     * @author xiul
     * 2018-1-22 上午12:00:42
     * Description 设备item - 选择设备类型，单选
     */
    @RequestMapping(params = "goChooseEquipmentType")
    public ModelAndView goChooseEquipmentType(HttpServletRequest request) {
        String uuid = request.getParameter("uuid");
        String id = request.getParameter("id");
        request.setAttribute("uuid", uuid);
        request.setAttribute("id", id);
        return new ModelAndView("com/zybk/cbsservice/cbsChooseEquipmentTypeForEsItem");
    }

    @RequestMapping(params = "getUuid")
    @ResponseBody
    public String getUuid() {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        return uuid;
    }

    @RequestMapping(params = "getItem")
    @ResponseBody
    public List<ZyEsItemEntity> getItem(HttpServletRequest request) {
        String id = request.getParameter("id");
        ZyEquipmentTypeEntity zyEquipmentType = systemService.getEntity(ZyEquipmentTypeEntity.class, id);
        if ("未知备件".equals(zyEquipmentType.getTypeDesc())) {
            return null;
        }
        String applyId = request.getParameter("applyId");
        List<String> equipmentType = new ArrayList<String>();
        if (applyId != null && !"".equals(applyId)) {
            equipmentType = systemService.findListbySql("select equipment_type from CBS_EQUIPMENT_APPLY where id=" + applyId + "'");
        }
        String cbsServiceId = request.getParameter("cbsServiceId");
        if (cbsServiceId != null && !"".equals(cbsServiceId)) {
            CbsServiceEntity cbsService = systemService.getEntity(CbsServiceEntity.class, cbsServiceId);
            if (StringUtil.isNotEmpty(cbsService.getZyEquipmentSpareId())) {
                equipmentType.add(cbsService.getZyEquipmentSpareId().getType().getTypeDesc());
            } else {
                equipmentType.add("");
            }
        }
        List<ZyEsItemEntity> hql = zyEsItemServiceI.findHql("from ZyEsItemEntity where type.id='" + id + "' and scope like'%" + equipmentType.get(0) + "%' order by item");
        return hql;
    }

    @RequestMapping(params = "getItemDesc")
    @ResponseBody
    public ZyEsItemEntity getItemDesc(HttpServletRequest request) {
        String id = request.getParameter("id");
        ZyEsItemEntity entity = zyEsItemServiceI.getEntity(ZyEsItemEntity.class, id);
        return entity;
    }

    @RequestMapping(params = "getShi")
    @ResponseBody
    public List<TSTerritory> getShi(HttpServletRequest request) {
        String sheng = request.getParameter("sheng");
        List<TSTerritory> shiHql = systemService.findHql("from TSTerritory where territoryCode like '" + sheng + "%' and territoryLevel='2'");
        return shiHql;
    }

    @RequestMapping(params = "getWarehouse")
    @ResponseBody
    public Map<String, Object> getWarehouse(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String type = request.getParameter("type");
        String id = request.getParameter("id");
        if ("1".equals(type) && StringUtil.isNotEmpty(id)) {
            CbsWarehouseEntity cbsWarehouse = systemService.getEntity(CbsWarehouseEntity.class, id);
            List<Object[]> tstList = systemService.findListbySql("select * from t_s_territory where id='" + cbsWarehouse.getSheng().getId() + "' or id='" + cbsWarehouse.getShi().getId() + "'");
            map.put("tstList", tstList);
            map.put("cbsWarehouse", cbsWarehouse);
        }
        List<CbsWarehouseEntity> warehouseHql = systemService.findHql("from CbsWarehouseEntity where isClose='0'");
        map.put("warehouseHql", warehouseHql);
        return map;
    }

    @RequestMapping(params = "addSparepartApply")
    @ResponseBody
    public AjaxJson addSparepartApply(HttpServletRequest request, CbsEquipmentApplyEntity cbsEquipmentApply) {
        AjaxJson j = new AjaxJson();
        //故障备件信息
        String[] type_ids = request.getParameterValues("type_ids");
        String[] type_dess = request.getParameterValues("type_dess");
        String[] item_ids = request.getParameterValues("item_ids");
        String[] itemms = request.getParameterValues("itemms");
        String[] s_ns = request.getParameterValues("s_ns");
        String[] equipment_ercodes = request.getParameterValues("equipment_ercodes");
        //申请备件
        String[] typeIds = request.getParameterValues("typeIds");
        String[] itemDescs = request.getParameterValues("itemDescs");

        String[] typeDess = request.getParameterValues("typeDess");
        String[] itemIds = request.getParameterValues("itemIds");
        String[] items = request.getParameterValues("items");
        String[] totals = request.getParameterValues("totals");
        String[] applyLayers = request.getParameterValues("applyLayers");
        String[] memos = request.getParameterValues("memos");
        String[] fileIds = request.getParameterValues("fileIds");
        String radiobutton = request.getParameter("radiobutton");
        String warehouse = request.getParameter("warehouse");
        String id = request.getParameter("serviceId");
        String seng = request.getParameter("seng");
        String si = request.getParameter("si");
        List<TSTerritory> shengList = systemService.findByProperty(TSTerritory.class, "territoryCode", seng);
        List<TSTerritory> shiList = systemService.findByProperty(TSTerritory.class, "territoryCode", si);
        cbsEquipmentApply.setSheng(shengList.get(0));
        cbsEquipmentApply.setShi(shiList.get(0));
        CbsServiceEntity cbsServiceEntity = cbsServiceService.getEntity(CbsServiceEntity.class, id);
        String fId = "";
        if (fileIds != null) {
            for (int i = 0; i < fileIds.length; i++) {
                fId += "," + fileIds[i];
            }
            cbsEquipmentApply.setFileId(fId.substring(1));
        }
        /*TSUser personLiable = cbsServiceEntity.getPersonLiable();
        if (personLiable != null) {
            TSUser tSUser = systemService.getEntity(TSUser.class, cbsServiceEntity.getPersonLiable().getId());
        }*/

        String status = cbsServiceEntity.getStatus();
        /*if ("3".equals(status)) {
            j.setSuccess(false);
        }*/
        //i.服务单未派单给第三方且由HD申请备件时：无需审批直接通过。提交备件申请时，确认页面红字提示【注意：此单未派单，申请备件将直接发货。】
        //获取登录的用户信息
        TSUser user = ResourceUtil.getSessionUserName();
        //用户的角色集合
        List<String> roleList = new ArrayList<>();
        List<TSRoleUser> tsRoleUserList = systemService.findHql("from TSRoleUser where TSUser.id='" + user.getId() + "'");
        for (TSRoleUser tsRoleUser : tsRoleUserList) {
            String role = tsRoleUser.getTSRole().getRoleCode();
            roleList.add(role);
        }

        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyyMMdd");
        String time = format.format(date);
        StringBuffer buffer = new StringBuffer();
        buffer.append("CO");
        buffer.append(time);
        List<Object[]> cbsEquipmentApplyList = systemService.findListbySql("select * from cbs_equipment_apply where to_days(create_date) = to_days(now()) ORDER BY record_id desc;");
        if ("否".equals(radiobutton)) {
            if (cbsEquipmentApplyList.size() == 0) {
                buffer.append("001");
                String s = buffer.toString();
                cbsEquipmentApply.setRecordId(s);
                List<TSTerritory> sheng = systemService.findByProperty(TSTerritory.class, "territoryCode", cbsEquipmentApply.getSheng().getTerritoryCode());
                cbsEquipmentApply.setSheng(sheng.get(0));
                List<TSTerritory> shi = systemService.findByProperty(TSTerritory.class, "territoryCode", cbsEquipmentApply.getShi().getTerritoryCode());
                /*if (StringUtil.isNotEmpty(cbsServiceEntity.getPersonLiable())) {
                    cbsEquipmentApply.setApproveUser(cbsServiceEntity.getPersonLiable().getId());
                }*/
                cbsEquipmentApply.setShi(shi.get(0));
                cbsEquipmentApply.setZt(2);
                if (roleList.contains("barcoHelpdesk") && !"3".equals(cbsServiceEntity.getStatus())) {
                    cbsEquipmentApply.setStatus(2);
                    j.setMsg("1");
                } else if (roleList.contains("barcoHelpdesk") && "3".equals(cbsServiceEntity.getStatus())) {
                    cbsEquipmentApply.setJudge(1);
                    cbsEquipmentApply.setStatus(1);
                } else if ((roleList.contains("thirdPartyEngineer") || roleList.contains("areaEngineer")) && "3".equals(cbsServiceEntity.getStatus())) {
                    cbsEquipmentApply.setJudge(2);
                    cbsEquipmentApply.setStatus(1);
                } else {
                    cbsEquipmentApply.setStatus(1);
                }
                if (cbsServiceEntity.getSr() != null) {
                    cbsEquipmentApply.setSrCode(cbsServiceEntity.getSr());
                }
                systemService.saveOrUpdate(cbsEquipmentApply);
            } else {
                String o = (String) cbsEquipmentApplyList.get(0)[1];
                String s = o.substring(10, 13);
                int i = Integer.parseInt(s);
                i++;
                if (i <= 9) {
                    buffer.append("00" + i);
                } else if (i >= 10 && i < 100) {
                    buffer.append("0" + i);
                } else {
                    buffer.append(i);
                }
                String string = buffer.toString();
                cbsEquipmentApply.setRecordId(string);
                List<TSTerritory> sheng = systemService.findByProperty(TSTerritory.class, "territoryCode", cbsEquipmentApply.getSheng().getTerritoryCode());
                cbsEquipmentApply.setSheng(sheng.get(0));
                List<TSTerritory> shi = systemService.findByProperty(TSTerritory.class, "territoryCode", cbsEquipmentApply.getShi().getTerritoryCode());
                cbsEquipmentApply.setShi(shi.get(0));
                /*if (StringUtil.isNotEmpty(cbsServiceEntity.getPersonLiable())) {
                    cbsEquipmentApply.setApproveUser(cbsServiceEntity.getPersonLiable().getId());
                }*/
                cbsEquipmentApply.setZt(2);
                if (roleList.contains("barcoHelpdesk") && !"3".equals(cbsServiceEntity.getStatus())) {
                    cbsEquipmentApply.setJudge(1);
                    cbsEquipmentApply.setStatus(2);
                    j.setMsg("1");
                } else if (roleList.contains("barcoHelpdesk") && "3".equals(cbsServiceEntity.getStatus())) {
                    cbsEquipmentApply.setJudge(1);
                    cbsEquipmentApply.setStatus(1);
                } else if ((roleList.contains("thirdPartyEngineer") || roleList.contains("areaEngineer")) && "3".equals(cbsServiceEntity.getStatus())) {
                    cbsEquipmentApply.setJudge(2);
                    cbsEquipmentApply.setStatus(1);
                } else {
                    cbsEquipmentApply.setStatus(1);
                }
                if (cbsServiceEntity.getSr() != null) {
                    cbsEquipmentApply.setSrCode(cbsServiceEntity.getSr());
                }
                systemService.saveOrUpdate(cbsEquipmentApply);
            }
        } else {
            if (cbsEquipmentApplyList.size() == 0) {
                buffer.append("001");
                String s = buffer.toString();
                cbsEquipmentApply.setRecordId(s);
                List<CbsWarehouseEntity> warehouseList = systemService.findByProperty(CbsWarehouseEntity.class, "id", warehouse);
                if (warehouseList.size() != 0) {
                    TSTerritory sheng = warehouseList.get(0).getSheng();
                    cbsEquipmentApply.setSheng(sheng);
                    TSTerritory shi = warehouseList.get(0).getShi();
                    cbsEquipmentApply.setShi(shi);
                    cbsEquipmentApply.setAddress(warehouseList.get(0).getAddress());
                    cbsEquipmentApply.setWarehouseId(warehouse);
                }
                /*if (StringUtil.isNotEmpty(cbsServiceEntity.getPersonLiable())) {
                    cbsEquipmentApply.setApproveUser(cbsServiceEntity.getPersonLiable().getId());
                }*/
                cbsEquipmentApply.setZt(1);
                if (roleList.contains("barcoHelpdesk") && !"3".equals(cbsServiceEntity.getStatus())) {
                    cbsEquipmentApply.setStatus(2);
                    j.setMsg("1");
                } else if (roleList.contains("barcoHelpdesk") && "3".equals(cbsServiceEntity.getStatus())) {
                    cbsEquipmentApply.setJudge(1);
                    cbsEquipmentApply.setStatus(1);
                } else if ((roleList.contains("thirdPartyEngineer") || roleList.contains("areaEngineer")) && "3".equals(cbsServiceEntity.getStatus())) {
                    cbsEquipmentApply.setJudge(2);
                    cbsEquipmentApply.setStatus(1);
                } else {
                    cbsEquipmentApply.setStatus(1);
                }
                if (cbsServiceEntity.getSr() != null) {
                    cbsEquipmentApply.setSrCode(cbsServiceEntity.getSr());
                }
                systemService.saveOrUpdate(cbsEquipmentApply);
            } else {
                String o = (String) cbsEquipmentApplyList.get(0)[1];
                String s = o.substring(10, 13);
                int i = Integer.parseInt(s);
                i++;
                if (i <= 9) {
                    buffer.append("00" + i);
                } else if (i >= 10 && i < 100) {
                    buffer.append("0" + i);
                } else {
                    buffer.append(i);
                }
                String string = buffer.toString();
                cbsEquipmentApply.setRecordId(string);
                List<CbsWarehouseEntity> warehouseList = systemService.findByProperty(CbsWarehouseEntity.class, "id", warehouse);
                if (warehouseList.size() != 0) {
                    TSTerritory sheng = warehouseList.get(0).getSheng();
                    cbsEquipmentApply.setSheng(sheng);
                    TSTerritory shi = warehouseList.get(0).getShi();
                    cbsEquipmentApply.setShi(shi);
                    cbsEquipmentApply.setAddress(warehouseList.get(0).getAddress());
                    cbsEquipmentApply.setWarehouseId(warehouse);
                }
                /*if (StringUtil.isNotEmpty(cbsServiceEntity.getPersonLiable())) {
                    cbsEquipmentApply.setApproveUser(cbsServiceEntity.getPersonLiable().getId());
                }*/
                cbsEquipmentApply.setZt(1);
                if (roleList.contains("barcoHelpdesk") && !"3".equals(cbsServiceEntity.getStatus())) {
                    j.setMsg("1");
                    cbsEquipmentApply.setStatus(2);
                } else if (roleList.contains("barcoHelpdesk") && "3".equals(cbsServiceEntity.getStatus())) {
                    cbsEquipmentApply.setJudge(1);
                    cbsEquipmentApply.setStatus(1);
                } else if ((roleList.contains("thirdPartyEngineer") || roleList.contains("areaEngineer")) && "3".equals(cbsServiceEntity.getStatus())) {
                    cbsEquipmentApply.setJudge(2);
                    cbsEquipmentApply.setStatus(1);
                } else {
                    cbsEquipmentApply.setStatus(1);
                }
                if (cbsServiceEntity.getSr() != null) {
                    cbsEquipmentApply.setSrCode(cbsServiceEntity.getSr());
                }
                systemService.saveOrUpdate(cbsEquipmentApply);
            }
        }
        //服务单日志
        List<String> listbySql2 = systemService.findListbySql("select record_id  from cbs_equipment_apply where create_name = '" + user.getRealName() + "' ORDER BY create_date desc LIMIT 0,1");
        cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, user.getRealName() + "提交备件申请&lt;" + listbySql2.get(0) + "&gt;。", null);


        //加入日志
        CbsServiceLogEntity cbsServiceLog = new CbsServiceLogEntity();
        cbsServiceLog.setCbsServiceId(cbsService);
        cbsServiceLog.setDescription("备件申请单中的附件");
        if (fileIds != null && fileIds.length != 0) {
            List<ZyFileLogEntity> zyFileLoghql = systemService.findHql("from ZyFileLogEntity  where business_type='F' AND createName='" + user.getRealName() + "' order by createDate desc");
            cbsServiceLog.setZyFileLogId(zyFileLoghql.get(0));
        }
        cbsServiceLog.setCbsServiceId(cbsServiceEntity);
        systemService.save(cbsServiceLog);

        CbsHandleLogEntity cbsHandleLog = new CbsHandleLogEntity();
        List<CbsEquipmentApplyEntity> cbsEquipmentApplyhql = systemService.findHql("from CbsEquipmentApplyEntity order by createDate desc");
        cbsHandleLog.setBusinessId(cbsEquipmentApplyhql.get(0).getId());
        cbsHandleLog.setLogType(1);
        cbsHandleLog.setDescription("创建了备件申请");
        systemService.save(cbsHandleLog);
        //备件申请详细
        if (typeIds != null) {
            for (int i = 0; i < typeIds.length; i++) {
                CbsEquipmentApplyDetailEntity applyDetailEntity = new CbsEquipmentApplyDetailEntity();
                ZyEquipmentTypeEntity zyEquipmentTypeEntity = systemService.getEntity(ZyEquipmentTypeEntity.class, typeIds[i]);
                applyDetailEntity.setTypeId(zyEquipmentTypeEntity);
                applyDetailEntity.setTypeDes(typeDess[i]);
                if (!"未知备件".equals(zyEquipmentTypeEntity.getTypeDesc())) {
                    ZyEsItemEntity entity = systemService.getEntity(ZyEsItemEntity.class, itemIds[i]);
                    applyDetailEntity.setItemId(entity);
                    if (entity != null) {
                        applyDetailEntity.setItemDesc(entity.getItemDesc());
                        applyDetailEntity.setItem(entity.getItem());
                    }
                } else {
                    applyDetailEntity.setItemDesc(itemDescs[i]);
                    applyDetailEntity.setItem(items[i].trim());
                    //通过备件号反查ID和Type并保存
                    List<ZyEsItemEntity> itemf = systemService.findHql("from ZyEsItemEntity where item='" + items[i].trim() + "'");
                    if (itemf.size() > 0) {
                        applyDetailEntity.setItemId(itemf.get(0));
                        applyDetailEntity.setItemDesc(itemf.get(0).getItemDesc());
                        applyDetailEntity.setItem(itemf.get(0).getItem());
                        ZyEquipmentTypeEntity Typef = itemf.get(0).getType();
                        if (Typef != null) {
                            applyDetailEntity.setTypeId(Typef);
                            applyDetailEntity.setTypeDes(Typef.getTypeDesc());
                        }
                    }

                }
                List<CbsEquipmentApplyEntity> hql = systemService.findHql("from CbsEquipmentApplyEntity order by createDate desc");
                applyDetailEntity.setApplyId(hql.get(0));
                if ("".equals(totals[i])) {
                    totals[i] = String.valueOf(0);
                }
                applyDetailEntity.setTotal(Integer.valueOf(totals[i]));
                applyDetailEntity.setApplyLayer(Integer.valueOf(applyLayers[i]));
                applyDetailEntity.setMemo(memos[i]);
                applyDetailEntity.setSn(cbsEquipmentApply.getSn());
                systemService.saveOrUpdate(applyDetailEntity);
            }
        }
        //返回备件申请单ID
        List<String> listbySql1 = systemService.findListbySql("select id  from cbs_equipment_apply where create_name='" + user.getRealName() + "' ORDER BY create_date desc LIMIT 0,1");
        if (fileIds != null) {
            for (int i = 0; i < fileIds.length; i++) {
                systemService.updateBySqlString("update zy_file_log set business_key = '" + listbySql1.get(0) + "' where id = '" + fileIds[i] + "'");
            }
        }
        if (roleList.contains("barcoHelpdesk") && !"3".equals(cbsServiceEntity.getStatus())) {
            Map<String, Object> attributes = new HashMap<String, Object>();
            attributes.put("applyId", listbySql1.get(0));
            j.setAttributes(attributes);
            pass(listbySql1.get(0));
        } else {
            //申请备件邮件提醒
            sendToCSA(cbsServiceEntity, listbySql2, user);
        }
        //存入故障备件
        cbsServiceService.addFaultEquipment(type_ids, type_dess, item_ids, itemms, s_ns, equipment_ercodes, user);
        //备件序列号验证
        //1、如果备件申请的设备序列号不存在，创建异常记录。由系统管理员创建设备序列号后关闭异常记录。
        boolean flag = cbsServiceService.snValiDate(id, s_ns);
        return j;
    }

    @RequestMapping(params = "addCsaAttention")
    @ResponseBody
    public AjaxJson csaAttention(HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        String id = req.getParameter("id");
        String csaAttention = req.getParameter("csaAttention");
        CbsEquipmentApplyEntity cbsEquipmentApply = systemService.getEntity(CbsEquipmentApplyEntity.class, id);
        cbsEquipmentApply.setCsaAttention(csaAttention);
        systemService.saveOrUpdate(cbsEquipmentApply);
        return j;
    }

    public void pass(String id) {
        try {
            TSUser user = ResourceUtil.getSessionUserName();
            CbsEquipmentApplyEntity cbsEquipmentApply = systemService.getEntity(CbsEquipmentApplyEntity.class, id);
            cbsEquipmentApply.setApproveUser(user.getId());
            systemService.saveOrUpdate(cbsEquipmentApply);
            /*APP通知*/
            CbsAppMessageEntity appMessage = new CbsAppMessageEntity();
            List<String> listbySql = systemService.findListbySql("select id from t_s_base_user where username = '" + cbsEquipmentApply.getCreateBy() + "'");
            String content = "您的备件申请" + cbsEquipmentApply.getRecordId() + "已审批通过，请等待物流安排发货。";
            appMessage.setContent(content);
            appMessage.setSender(user.getId());
            appMessage.setReciver(listbySql.get(0));
            appMessage.setState(StaticValue.DIC_APP_MESSAGE_STATE_UNREAD);
            systemService.save(appMessage);
            systemService.addLog("新增APP消息,接受方:" + listbySql.get(0) + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
            //如果该备件申请关联的服务单没有SR号，则向SFDC发送创单邮件
            sendEmailToSFDC(cbsEquipmentApply);
            //加入日志
            CbsHandleLogEntity cbsHandleLog = new CbsHandleLogEntity();
            cbsHandleLog.setBusinessId(id);
            cbsHandleLog.setLogType(1);
            cbsHandleLog.setDescription("通过了备件申请");
            systemService.save(cbsHandleLog);
            //自动创建发货单
            cbsServiceAssignListService.autoDoAdd(id, user.getRealName());
            /*备件申请审批通过,向CSA发送短信和邮件通知*/
            sendEmailToCSA(id);
            /*备件申请审批通过后两个小时（该时限可以人为设置）后，发货单状态仍是“CSA待发货”，则向CSA发送短信和邮件通知。*/
            selectStatus1(id);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("事务出现异常,回滚事务！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //此处采用手动回滚
        }
    }
    /*备件申请审批通过后两个小时（该时限可以人为设置）后，发货单状态仍是“CSA待发货”，则向CSA发送短信和邮件通知。*/

    public void selectStatus1(final String id) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                List<CbsDelinerEntity> cbsDelinerHql = systemService.findHql("from CbsDelinerEntity where status=1 and equipmentApplyId.id = '" + id + "' order by createDate desc");
                if (cbsDelinerHql.size() != 0) {
                    CbsEquipmentApplyEntity cbsEquipmentApply = systemService.getEntity(CbsEquipmentApplyEntity.class, id);
                    //获取服务商信息
                    List<String> shortnameList = systemService.findListbySql("select d.shortname from t_s_depart d left join cbs_service cbs on d.org_code = cbs.service_provider_code where cbs.id='" + cbsEquipmentApply.getServiceId() + "'");
                    List<CbsServiceEntity> cbsServiceList = systemService.findHql("from CbsServiceEntity where id='" + cbsEquipmentApply.getServiceId() + "'");
                    List<TSUser> hql = systemService.findHql("from TSUser where id='" + cbsEquipmentApply.getApproveUser() + "'");
                    List<String> mobilePhoneList = systemService.findListbySql("select mobilePhone from t_s_user u LEFT JOIN t_s_base_user bu on u.id = bu.id where bu.username = '" + cbsEquipmentApply.getCreateBy() + "'");
                    String shortname = "";
                    if (shortnameList.size() != 0) {
                        shortname = shortnameList.get(0);
                    }
                    String emailTital = "备件发货超时提醒：<" + cbsDelinerHql.get(0).getCode() + ">-<" + cbsServiceList.get(0).getLevel() + ">-<" + cbsServiceList.get(0).getCode() + ">-<" + cbsServiceList.get(0).getZyCinemaName() + ">-" + getDateStr(new Date());
                    String emailContent = "Dear CSA同事们，发货单:<" + cbsDelinerHql.get(0).getCode() + ">尚未发货，请及时处理。\n" +
                            "发货单号：<" + cbsDelinerHql.get(0).getCode() + ">。\n" +
                            "备件申请人：<" + shortname + "> <" + cbsEquipmentApply.getCreateName() + "> <" + mobilePhoneList.get(0) + ">。\n" +
                            "备件审批人： <" + hql.get(0).getRealName() + "> <" + hql.get(0).getMobilePhone() + ">。\n" +
                            "具体内容请查看http://cbs.cfg-barco.com\n" +
                            "\n" +
                            "* 该邮件请勿回复";
                    List<String> listbySql = systemService.findListbySql("select email from t_s_user u LEFT JOIN t_s_role_user ru ON u.id=ru.userid LEFT JOIN t_s_role r ON ru.roleid=r.id LEFT JOIN t_s_base_user b on b.id = u.id where b.`status` = '" + Globals.User_Normal + "' and r.rolecode='" + StaticValue.RULE_CODE_BARCO_CSA_ZB + "'");
                    for (int i = 0; i < listbySql.size(); i++) {
                        SendMailUtil.sendeMail(listbySql.get(i), emailTital, emailContent, systemService);
                    }
                    List<String> listbySql1 = systemService.findListbySql("select mobilePhone from t_s_user u LEFT JOIN t_s_role_user ru ON u.id=ru.userid LEFT JOIN t_s_role r ON ru.roleid=r.id LEFT JOIN t_s_base_user b on b.id = u.id where b.`status` = '" + Globals.User_Normal + "' and r.rolecode='" + StaticValue.RULE_CODE_BARCO_CSA_ZB + "'");
                	// add start 190125 Amy 9点30之前和21点之后不提醒
                	Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    int hour = calendar.get(Calendar.HOUR_OF_DAY);
                    int minutes = calendar.get(Calendar.MINUTE);
                	if (hour < 9 || hour >= 21 || (hour == 9 && minutes < 30)) {
                	} else {
	                    for (int i = 0; i < listbySql1.size(); i++) {
	                        SendMessage.sendSMSWithContent(listbySql1.get(i), "发货单号<" + cbsDelinerHql.get(0).getCode() + ">尚未发货，请及时处理。详情请查看CBS系统", systemService);
	                    }
                	}
                	// add end 190125 Amy 9点30之前和21点之后不提醒
                }
            }
        }, StaticValue.selectStatusTiem);
    }

    /*备件申请审批通过*/
    public void sendEmailToCSA(final String id) throws Exception {
        List<CbsDelinerEntity> cbsDelinerHql = systemService.findHql("from CbsDelinerEntity where status=1 and equipmentApplyId.id = '" + id + "' order by createDate desc");
        CbsEquipmentApplyEntity cbsEquipmentApply = systemService.getEntity(CbsEquipmentApplyEntity.class, id);
        List<CbsServiceEntity> cbsServiceList = systemService.findHql("from CbsServiceEntity where id='" + cbsEquipmentApply.getServiceId() + "'");
        List<TSUser> hql = systemService.findHql("from TSUser where id='" + cbsEquipmentApply.getApproveUser() + "'");
        TSUser user = ResourceUtil.getSessionUserName();
        if ("1".equals(cbsDelinerHql.get(0).getStatus())) {
            Calendar now = Calendar.getInstance();
            //一周第一天是否为星期天
            boolean isFirstSunday = (now.getFirstDayOfWeek() == Calendar.SUNDAY);
            int weekDay = now.get(Calendar.DAY_OF_WEEK);
            //若一周第一天为星期天，则-1
            if (isFirstSunday) {
                weekDay = weekDay - 1;
                if (weekDay == 0) {
                    weekDay = 7;
                }
            }
            int hour = now.get(Calendar.HOUR_OF_DAY);
            if (weekDay == 7 || weekDay == 6 || hour < 8 || hour > 18) {
                List<String> listbySql1 = systemService.findListbySql("select mobilePhone from t_s_user u LEFT JOIN t_s_role_user ru ON u.id=ru.userid LEFT JOIN t_s_role r ON ru.roleid=r.id LEFT JOIN t_s_base_user b on b.id = u.id where b.`status` = '" + Globals.User_Normal + "' and r.rolecode='" + StaticValue.RULE_CODE_BARCO_CSA_ZB + "'");
                for (int i = 0; i < listbySql1.size(); i++) {
                    SendMessage.sendSMSWithContent(listbySql1.get(i), "CSA同事们，请安排以下发货。发货单号：<" + cbsDelinerHql.get(0).getCode() + ">。备件审批人：<" + hql.get(0).getRealName() + " " + hql.get(0).getMobilePhone() + ">。具体内容请查看CBS系统", systemService);
                }
            }

            //获取服务商信息
            List<String> shortnameList = systemService.findListbySql("select d.shortname from t_s_depart d left join cbs_service cbs on d.org_code = cbs.service_provider_code where cbs.id='" + cbsEquipmentApply.getServiceId() + "'");
            String shortname = "";
            if (shortnameList.size() != 0) {
                shortname = shortnameList.get(0);
            }
            String emailTital = "备件发货申请：<" + cbsDelinerHql.get(0).getCode() + ">-<" + cbsServiceList.get(0).getLevel() + ">-<" + cbsServiceList.get(0).getCode() + ">-<" + cbsServiceList.get(0).getZyCinemaName() + ">-" + getDateStr(new Date());
            String emailContent = "Dear CSA同事们，请安排以下发货。\n" +
                    "发货单号：<" + cbsDelinerHql.get(0).getCode() + ">。\n" +
                    "备件申请人：<" + shortname + "> <" + user.getRealName() + "> <" + user.getMobilePhone() + ">。\n" +
                    "备件审批人： <" + hql.get(0).getRealName() + "> <" + hql.get(0).getMobilePhone() + ">。\n" +
                    "具体内容请查看http://cbs.cfg-barco.com\n" +
                    "\n" +
                    "* 该邮件请勿回复";
            List<String> listbySql = systemService.findListbySql("select email from t_s_user u LEFT JOIN t_s_role_user ru ON u.id=ru.userid LEFT JOIN t_s_role r ON ru.roleid=r.id  LEFT JOIN t_s_base_user b on b.id = u.id where  b.`status` = '" + Globals.User_Normal + "' and r.rolecode='" + StaticValue.RULE_CODE_BARCO_CSA_ZB + "'");
            for (int i = 0; i < listbySql.size(); i++) {
                SendMailUtil.sendeMail(listbySql.get(i), emailTital, emailContent, systemService);
            }
        }
    }

    //如果该备件申请关联的服务单没有SR号，则向SFDC发送创单邮件
    public void sendEmailToSFDC(CbsEquipmentApplyEntity cbsEquipmentApply) {
//        CbsServiceEntity cbsService = systemService.getEntity(CbsServiceEntity.class, cbsEquipmentApply.getServiceId());
//        if (StringUtil.isEmpty(cbsService.getSr())) {
//            List<CbsEquipmentApplyDetailEntity> cbsEquipmentApplyDetailHql = systemService.findHql("from CbsEquipmentApplyDetailEntity where applyId='" + cbsEquipmentApply.getId() + "'");
//            StringBuffer itemBuffer = new StringBuffer();
//            StringBuffer totalBuffer = new StringBuffer();
//            for (int i = 0; i < cbsEquipmentApplyDetailHql.size(); i++) {
//                itemBuffer.append("," + cbsEquipmentApplyDetailHql.get(i).getItem());
//                totalBuffer.append("," + cbsEquipmentApplyDetailHql.get(i).getTotal());
//            }
//            String s = itemBuffer.toString().substring(1, itemBuffer.toString().length());
//            String s1 = "";
//            if (totalBuffer.toString().length() > 2) {
//                s1 = totalBuffer.toString().substring(1, totalBuffer.toString().length());
//            } else {
//                String[] split = totalBuffer.toString().split(",");
//                s1 = split[1];
//            }
//            List<String> snList = systemService.findListbySql("select type_desc from zy_equipment_type where id=(select type from zy_equipment_spare where sn='" + cbsService.getSn() + "')");
//            String serviceType1 = "";
//            String serviceType2 = "";
//            String errorType1 = "";
//            String errorType2 = "";
//            String sn = "";
//            if (snList.size() != 0 && StringUtil.isNotEmpty(snList.get(0))) {
//                sn = snList.get(0);
//            }
//            if (cbsService.getServiceType1() != null && cbsService.getServiceType2() != null) {
//                serviceType1 = cbsService.getServiceType1().getName();
//                serviceType2 = cbsService.getServiceType2().getName();
//            }
//            if (cbsService.getErrorType1() != null && cbsService.getErrorType2() != null) {
//                errorType1 = cbsService.getErrorType1().getName();
//                errorType2 = cbsService.getErrorType2().getName();
//            }
//            String bp = "";
//            List<String> bpList = systemService.findListbySql("select bp_no from zy_equipment_spare where sn='" + cbsService.getSn().trim() + "'");
//            if (bpList.size() != 0 && StringUtil.isNotEmpty(bpList.get(0))) {
//                bp = bpList.get(0);
//            }
//            String emailTital = "NewSR <" + serviceType1 + "," + serviceType2 + ">-<" + cbsService.getCode() + ">-<" + cbsService.getZyCinemaName() + ">";
//            String emailContent = " 影院名称：" + cbsService.getZyCinemaName() + "\n" +
//                    "服务单号：" + cbsService.getCode() + "\n" +
//                    "设备序列号：" + cbsService.getSn() + "\n" +
//                    "BP：" + bp + "\n" +
//                    "联系人：" + cbsService.getContactsName() + " - " + cbsService.getContactsPhone() + "\n" +
//                    "产品分类：" + sn + "\n" +
//                    "故障分类1：" + errorType1 + "\n" +
//                    "故障分类2：" + errorType2 + "\n" +
//                    "级别：" + cbsService.getLevel() + "\n" +
//                    "故障描述：" + cbsService.getDescription() + "\n" +
//                    "报修时间：" + cbsService.getCreateDate() + "\n" +
//                    "备件申请：备件号:" + s + " 数量: " + s1 + "";
//            SendMailUtil.sendeMail("service.DC.china@barco.com", emailTital, emailContent, systemService);
//            getSr(cbsService.getId());
//        }
    }

    @RequestMapping(params = "dispatch")
    public ModelAndView dispatch(HttpServletRequest request) {
        String id = request.getParameter("cbsServiceId");
        request.setAttribute("cbsServiceId", id);
        return new ModelAndView("com/zybk/cbsservice/cbsServiceDispatch");
    }

    @RequestMapping(params = "changeStatus")
    @ResponseBody
    public AjaxJson changeStatus(String id, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        String fou = request.getParameter("fou");
        List<CbsEquipmentApplyEntity> serviceId = systemService.findHql("from CbsEquipmentApplyEntity where serviceId='" + id + "' order by createDate desc");
        if ("fou".equals(fou)) {
            String sid = request.getParameter("id");
            if (serviceId.size() >= 1) {
                serviceId.get(0).setStatus(2);
                serviceId.get(0).setMemo("HD申请备件");
                systemService.saveOrUpdate(serviceId.get(0));
            }
            //如果该备件申请关联的服务单没有SR号，则向SFDC发送创单邮件
            CbsServiceEntity cbsServiceEntity = systemService.getEntity(CbsServiceEntity.class, serviceId.get(0).getServiceId());
            if (cbsServiceEntity.getSr() == null || "".equals(cbsServiceEntity.getSr())) {
                //SendMailUtil.sendeMail("service.DC.china@barco.com", "备件审批通过-" + cbsService.getCode() + "-" + cbsService.getZyCinemaName() + "-" + cbsService.getSn(), "备件审批通过", systemService);
                //getSr(cbsServiceEntity);
            }
        } else {
            if (serviceId.size() >= 1) {
                serviceId.get(0).setStatus(1);
                systemService.saveOrUpdate(serviceId.get(0));
            }
        }
        String applyId = serviceId.get(0).getId();
        j.setSuccess(true);
        j.setMsg(applyId);
        return j;
    }

    /**
     * 获取编辑页面服务商处理时间
     *
     * @return
     */
    @RequestMapping(params = "getServiceProvidersDealTime")
    @ResponseBody
    public AjaxJson getServiceProvidersDealTime(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        String cbsServiceId = request.getParameter("cbsServiceId");
        String dealWithTiem = "0";
        List<Map<String, Object>> results = systemService.findForJdbc("SELECT cbs.id AS 'id', " +
                "IFNULL( concat( IF ( cbs.`SPEED_STATUS` = 7, " +
                "TIMESTAMPDIFF( HOUR, cbs.assign_time, cbs.close_time ), " +
                "TIMESTAMPDIFF(HOUR, cbs.assign_time, NOW())), '小时' ), '' ) " +
                "AS dealWithTiem " +
                "FROM `cbs_service` cbs WHERE 1 = 1 AND cbs.id = '" + cbsServiceId + "'");

        if (results.size() > 0) {
            Map map = results.get(0);
            if (StringUtil.isNotEmpty(map.get("dealWithTiem"))) {
                dealWithTiem = map.get("dealWithTiem").toString();
            }
        }
        ajaxJson.setObj(dealWithTiem);
        return ajaxJson;
    }


    /**
     * 附件预览页面打开链接
     *
     * @return
     */
    @RequestMapping(params = "openViewFile")
    public ModelAndView openViewFile(HttpServletRequest request) {
        String fileid = request.getParameter("fileid");
        ZyFileLogEntity zyFileLogEntity = zyFileLogServiceI.get(ZyFileLogEntity.class, fileid);
        String subclassname = oConvertUtils.getString(request.getParameter("subclassname"), "org.jeecgframework.web.system.pojo.base.ZyFileLogEntity");
        String contentfield = oConvertUtils.getString(request.getParameter("contentfield"));
        Class fileClass = MyClassLoader.getClassByScn(subclassname);// 附件的实际类
        Object fileobj = systemService.getEntity(fileClass, fileid);
        ReflectHelper reflectHelper = new ReflectHelper(fileobj);
        String realpath = zyFileLogEntity.getFilePath();
        request.setAttribute("realpath", realpath);
        request.setAttribute("fileid", fileid);
        request.setAttribute("subclassname", subclassname);
        request.setAttribute("contentfield", contentfield);
        return new ModelAndView("common/upload/imageView");

    }

    /**
     * 根据sn判断是不是服务器设备
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "dontService")
    public AjaxJson dontService(HttpServletRequest request, HttpServletResponse response) {
        AjaxJson ajaxJson = new AjaxJson();
        String sn = request.getParameter("sn");
        if (StringUtil.isNotEmpty(sn)) {
            List<Map<String, Object>> results = cbsServiceService.dontService(sn);
            if (results.size() > 0) {
                if (results.get(0).get("type").equals("Y")) {
                    ajaxJson.setSuccess(true);
                }
                if (results.get(0).get("type").equals("N")) {
                    ajaxJson.setSuccess(false);
                }
            } else {
                ajaxJson.setMsg("S");
                ajaxJson.setSuccess(true);
            }
        }
        return ajaxJson;
    }

    /**
     * @param request
     * @param orgCode         组织机构code
     * @param cbsId           服务单id
     * @param contactPosition 联系人职位
     * @return
     * @author xiul
     * 2016-4-18 上午9:51:16
     * Description 根据组织机构id和联系人职位(岗位)查询对应人员
     */
    @ResponseBody
    @RequestMapping(params = "queryTPServerBusinessr")
    public AjaxJson queryTPServerBusinessr(HttpServletRequest request,
                                           @RequestParam(value = "orgCode") String orgCode,
                                           @RequestParam(value = "cbsId") String cbsId,
                                           @RequestParam(value = "contactPosition") String contactPosition) {
        AjaxJson j = new AjaxJson();
        try {
            Map map = new HashMap();
            //获取服务商基本信息
            List<ZyContactsEntity> zyContacts = zyCommonService.queryUsersByConditions(orgCode, StaticValue.RULE_CODE_THIRDPARTY_HEADER, StaticValue.DIC_BUS_SCOPE_INSPECTION, contactPosition);
            map.put("zyContacts", zyContacts);
            //获取派单的工程师和派单要求，以及服务商处理时间
            if (StringUtil.isNotEmpty(cbsId)) {
                List<Map<String, Object>> objects = cbsServiceService.getContactsById(cbsId);
                map.put("objects", objects);
            }
            j.setAttributes(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return j;
    }


    /**
     * APP端，维修列表
     */
    @ResponseBody
    @RequestMapping(params = "queryAppServiceTpList")
    public AjaxJson queryAppServiceTpList(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        Map<String, Object> rtMap = new HashMap<String, Object>();
        int pageSize = 5; //默认每次刷新就多加载5条数据
        String styletype = oConvertUtils.getString(request.getParameter("styletype")); //维修单类型
        int type = oConvertUtils.getInt(oConvertUtils.getString(request.getParameter("type"))); //1：待分配 2：已分配
        String area = oConvertUtils.getString(request.getParameter("area"));
        String planYear = oConvertUtils.getString(request.getParameter("planYear"));
        String planMonth = oConvertUtils.getString(request.getParameter("planMonth"));
        String esSn = oConvertUtils.getString(request.getParameter("esSn"));
        String cmId = oConvertUtils.getString(request.getParameter("cmId"));
        int counters = oConvertUtils.getInt(request.getParameter("counters"));
        Map<String, Object> ipTpListMap = cbsServiceService.queryAppIpTpList("", styletype, type, area, planYear, planMonth, esSn, cmId, counters, pageSize);
        rtMap.put("ipTpListMap", ipTpListMap);
        j.setAttributes(rtMap);
        return j;
    }

    /**
     * APP端，维修列表
     */
    @ResponseBody
    @RequestMapping(params = "queryAppServiceAegTpList")
    public AjaxJson queryAppServiceAegTpList(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        Map<String, Object> rtMap = new HashMap<String, Object>();
        String styletype = oConvertUtils.getString(request.getParameter("styletype")); //维修单类型
        int type = oConvertUtils.getInt(oConvertUtils.getString(request.getParameter("type")));
        String area = oConvertUtils.getString(request.getParameter("area"));
        String planYear = oConvertUtils.getString(request.getParameter("planYear"));
        String planMonth = oConvertUtils.getString(request.getParameter("planMonth"));
        String esSn = oConvertUtils.getString(request.getParameter("esSn"));
        String cmId = oConvertUtils.getString(request.getParameter("cmId"));
        Map<String, Object> ipTpListMap = cbsServiceService.queryAppIpTpAegList("", styletype, type, area, planYear, planMonth, esSn, cmId);
        rtMap.put("ipTpListMap", ipTpListMap);
        j.setAttributes(rtMap);
        return j;
    }

    /**
     * APP端，维修列表
     */
    @ResponseBody
    @RequestMapping(params = "queryAppServiceTpEgList")
    public AjaxJson queryAppServiceTpEgList(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        Map<String, Object> rtMap = new HashMap<String, Object>();
        String styletype = oConvertUtils.getString(request.getParameter("styletype")); //维修单类型
        int type = oConvertUtils.getInt(oConvertUtils.getString(request.getParameter("type")));
        String area = oConvertUtils.getString(request.getParameter("area"));
        String planYear = oConvertUtils.getString(request.getParameter("planYear"));
        String planMonth = oConvertUtils.getString(request.getParameter("planMonth"));
        String esSn = oConvertUtils.getString(request.getParameter("esSn"));
        String cmId = oConvertUtils.getString(request.getParameter("cmId"));
        Map<String, Object> ipTpListMap = cbsServiceService.queryAppIpTpEgList("", styletype, type, area, planYear, planMonth, esSn, cmId);
        rtMap.put("ipTpListMap", ipTpListMap);
        j.setAttributes(rtMap);
        return j;
    }

    /**
     * APP端，查找分配任务个数以及服务商code
     */
    @ResponseBody
    @RequestMapping(params = "goAppTpSendIp")
    public AjaxJson goAppTpSendIp(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        Map<String, Object> rsMap = new HashMap<String, Object>();
        String planIds = oConvertUtils.getString(request.getParameter("planIds"));
        rsMap.put("planIds", planIds);
        String[] ids = planIds.split(",");
        if (ids != null && ids.length > 0) {
            if (StringUtil.isNotEmpty(ids[0])) {
                List<Map<String, Object>> list = systemService.findForJdbc("SELECT service_provider_code FROM cbs_service WHERE id = '" + ids[0].toString() + "'");
                rsMap.put("company", list.get(0).get("service_provider_code")); //第三方服务商
                rsMap.put("ipCount", ids.length);
            }
        }
        j.setAttributes(rsMap);
        return j;
    }

    /**
     * @author xiul
     * 2016-8-15 下午8:31:35
     * Description APP - 第三方分派巡检计划页 - 根据选择角色不同查询
     */
    @ResponseBody
    @RequestMapping(params = "queryEngineerForAppSendIp")
    public AjaxJson queryEngineerForAppSendIp(HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        String type = oConvertUtils.getString(req.getParameter("type"));
        String planIds = oConvertUtils.getString(req.getParameter("planIds"));
        String company = oConvertUtils.getString(req.getParameter("company"));
        DataGrid dataGrid = new DataGrid();
        if (type.equals("1")) { //商务
            cbsServiceService.queryDatagridResultForChooseContacters(req, dataGrid, company);
        }
        if (type.equals("2")) {  //区域工程师
            cbsServiceService.queryDatagridResultForChooseEngineers(req, dataGrid, company, planIds);
        }
        if (type.equals("3")) { //工程师
            cbsServiceService.queryDatagridResultForChooseEgEnter(req, dataGrid, company, planIds);
        }
        j.setObj(dataGrid.getResults());
        return j;
    }

    /**
     * @author xiul
     * 2016-8-15 下午8:31:35
     * Description APP - 根据工程师id，获取工程师详细信息
     */
    @ResponseBody
    @RequestMapping(params = "queryEngineerForAppEngName")
    public AjaxJson queryEngineerForAppEngName(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = req.getParameter("id");
        if (StringUtil.isNotEmpty(id)) {
            List<Map<String, Object>> list = cbsServiceService.queryEngineerForAppEngName(id);
            /*获取未完成个数*/
            List<Map<String, Object>> list1 = cbsServiceService.queryEngineerWsizeForAppEngName(id);
            if (list.size() > 0) {
                list.get(0).put("wsize", list1.get(0).get("wsize"));
                ajaxJson.setAttributes(list.get(0));
            }
        }
        return ajaxJson;
    }


    @ResponseBody
    @RequestMapping(params = "queryAegEngineerForApp")
    public AjaxJson queryAegEngineerForApp(HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        String type = oConvertUtils.getString(req.getParameter("type"));
        String planIds = oConvertUtils.getString(req.getParameter("planIds"));
        String company = oConvertUtils.getString(req.getParameter("company"));
        DataGrid dataGrid = new DataGrid();
        if (type.equals("1")) { //商务
            cbsServiceService.queryDatagridResultForChooseContacters(req, dataGrid, company);
        }
        if (type.equals("2")) {  //区域工程师
            cbsServiceService.queryDatagridResultForChooseEngineers(req, dataGrid, company, planIds);
        }
        if (type.equals("3")) { //工程师
            cbsServiceService.queryDatagridResultForChooseEgEnter(req, dataGrid, company, planIds);
        }
        j.setObj(dataGrid.getResults());
        return j;
    }

    /**
     * @author xiul
     * 2016-8-15 下午8:31:35
     * Description APP - 根据服务单id，获取服务单详情
     */
    @ResponseBody
    @RequestMapping(params = "getDetailByCbsId")
    public AjaxJson getDetailByCbsId(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = req.getParameter("id");
        if (StringUtil.isNotEmpty(id)) {
            HashMap map = new HashMap();
            //基本信息
            List<Map<String, Object>> list = cbsServiceService.getCbsAPPServiceByCid(id);
            //附加任务信息
            List<Map<String, Object>> cbsServiceTaskMap = cbsServiceTaskMapServiceI.findForJdbc("SELECT\n" +
                    "\tdistinct(t.id) AS id,\n" +
                    "\tt.content \n" +
                    "FROM\n" +
                    "\tCBS_SERVICE_TASK_MAP m\n" +
                    "LEFT JOIN cbs_attach_task t ON t.id = m.attach_task_id\n" +
                    "WHERE\n" +
                    "\tm.service_id = ?", id);
            //处理日志
            List<Map<String, Object>> cbsServiceLogList = cbsServiceLogServiceI.getServiceLogOfTp(id);

            //备件设备基本信息
            String sql = "SELECT\n" +
                    "\tIFNULL(cbs.sn, '') AS sn,\n" +
                    "\tIFNULL(t.TYPE_DESC, '') AS type,\n" +
                    "\tIFNULL(cbs.`code`, '') AS `code`,\n" +
                    "\tIFNULL(cbs.so, '') AS so\n" +
                    "FROM\n" +
                    "\tcbs_service cbs\n" +
                    "LEFT JOIN zy_equipment_spare s ON cbs.sn = s.sn\n" +
                    "LEFT JOIN zy_equipment_type t ON t.id = s.type" +
                    " WHERE cbs.id='" + id + "'";
            List<Map<String, Object>> cbsServiceEntity = cbsServiceService.findForJdbc(sql);
            map.put("cbsServiceEntity", cbsServiceEntity.get(0)); //服务单基本信息

            //获取申请的备件信息
            List<CbsEquipmentApplyEntity> cbsEquipmentApplyList = systemService.findHql("from CbsEquipmentApplyEntity where serviceId='" + id + "'");
            if (cbsEquipmentApplyList.size() > 0) {
                for (CbsEquipmentApplyEntity cbsEquipmentApplyEntity : cbsEquipmentApplyList) {
                    String s = "SELECT\n" +
                            "\td.id AS id,\n" +
                            "\tIFNULL(d.type_des,'') AS typedes,\n" +
                            "\tIFNULL(d.item,'') AS item,\n" +
                            "\tIFNULL(CASE cd.`status`\n" +
                            "WHEN '1' THEN\n" +
                            "\t'CSA待发货'\n" +
                            "WHEN '2' THEN\n" +
                            "\t'CSA已发货'\n" +
                            "WHEN '3' THEN\n" +
                            "\t'CSA取消发货'\n" +
                            "WHEN '4' THEN\n" +
                            "\t\t\t'欠货中'\n" +
                            "\t\tWHEN '5' THEN\n" +
                            "\t\t\t'物流待发货'\n" +
                            "\t\tWHEN '6' THEN\n" +
                            "\t\t\t'物流已发货'\n" +
                            "\t\tWHEN '7' THEN\n" +
                            "\t\t\t'签收'\n" +
                            "END,'') AS `status`,\n" +
                            "IFNULL( cd.expecttime,'') AS expecttime\n" +
                            "FROM\n" +
                            "\tcbs_equipment_apply_detail d\n" +
                            "LEFT JOIN CBS_EQUIPMENT_APPLY a ON a.id = d.apply_id \n" +
                            "LEFT JOIN CBS_DELIVER cd ON cd.equipment_apply_id = a.id\n" +
                            "WHERE\n" +
                            "\ta.id='" + cbsEquipmentApplyEntity.getId() + "'";
                    List<Map<String, Object>> list1 = systemService.findForJdbc(s);
                    cbsEquipmentApplyEntity.setCbsDeliveList(list1);

                    String SQL1 = "select  IFNULL( timestampdiff( MINUTE, now(),ADDDATE( create_date, INTERVAL 2 HOUR )), '0' ) AS min FROM\t CBS_EQUIPMENT_APPLY WHERE id = '" + cbsEquipmentApplyEntity.getId() + "'";
                    List<Map<String, Object>> list2 = systemService.findForJdbc(SQL1);
                    if (list2.size() > 0) {
                        cbsEquipmentApplyEntity.setEqDate(StringUtil.isNotEmpty(list2.get(0).get("min")) ? list2.get(0).get("min").toString() : "");
                    }
                }
            }

            //查询完工报告签到记录
            String sl = "SELECT CONCAT('第', num, '次') AS num, DATE_FORMAT(date, '%Y-%m-%d %H:%i:%s') AS date FROM arrival_of_abnormal WHERE service_id = '" + id + "'";
            List<Map<String, Object>> arrivalofabnormallist = systemService.findForJdbc(sl);
            map.put("arrivalofabnormallist", arrivalofabnormallist);//完工报告签到次数
            map.put("cbsEquipmentApplyList", cbsEquipmentApplyList);  //备件申请单
            map.put("list", list.get(0));
            map.put("cbsServiceTaskMap", cbsServiceTaskMap);
            map.put("cbsServiceLogList", cbsServiceLogList);

            ajaxJson.setAttributes(map);
        }
        return ajaxJson;
    }

    /**
     * @author xiul
     * 2016-8-15 下午8:31:35
     * Description APP - 根据服务单id，获取备件和服务单信息
     */
    @ResponseBody
    @RequestMapping(params = "getEquipmentByCbsId")
    public AjaxJson getEquipmentByCbsId(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = req.getParameter("id");
        if (StringUtil.isNotEmpty(id)) {
            HashMap map = new HashMap();

            ajaxJson.setAttributes(map);
        }
        return ajaxJson;
    }


    /**
     * @author xiul
     * 2016-8-15 下午8:31:35
     * Description APP - 根据服务单id，获取完工报告信息
     */
    @ResponseBody
    @RequestMapping(params = "getLookReportByCbsId")
    public AjaxJson getLookReportByCbsId(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = req.getParameter("id");
        String type = req.getParameter("type");
        Map map = new HashMap();
        try {
            if (StringUtil.isNotEmpty(id)) {
//                if (StringUtil.isNotEmpty(type)&&"wx".equals(type)){
                List<Map<String, Object>> o = systemService.findForJdbc("SELECT\n" +
                        "	IFNULL(cbs.id, '') AS id,\n" +
                        "	IFNULL(cbs.sn, '') AS sn,\n" +
                        "	IFNULL(cbs.`level`, '') AS `level`,\n" +
                        "	IFNULL(cbs.`code`, '') AS `code`,\n" +
                        "	IFNULL(cbs.sr, '') AS sr,\n" +
                        "	IFNULL(cbs.so, '') AS so,\n" +
                        "	IFNULL(cbs.description, '') AS description,\n" +
                        "	IFNULL(cbs.handle_des, '') AS jf,\n" +
                        "	IFNULL(cbs.assign_time, '') AS assignTime,\n" +
                        "	IFNULL(cbs.`zy_cinema_name`, '') AS `cinemaName`,\n" +
                        "	IFNULL(cbs.address, '') AS address,\n" +
                        "	IFNULL(cbs.type_intheater_name, '') AS typeName,\n" +
                        "	IFNULL(cbs.contacts_name, '') AS `name`,\n" +
                        "	IFNULL(cbs.contacts_phone, '') AS phone,\n" +
                        "	IFNULL(\n" +
                        "		DATE_FORMAT(\n" +
                        "			cbs.order_time_agin,\n" +
                        "			'%Y-%m-%d'\n" +
                        "		),\n" +
                        "		IFNULL(\n" +
                        "			DATE_FORMAT(cbs.order_time, '%Y-%m-%d'),\n" +
                        "			''\n" +
                        "		)\n" +
                        "	) AS orderTime,\n" +
                        "	IFNULL(\n" +
                        "		DATE_FORMAT(MAX(re.actual_time), '%Y-%m-%d'),\n" +
                        "		''\n" +
                        "	) AS acyualTime,\n" +
                        "	IFNULL(\n" +
                        "		DATE_FORMAT(MAX(ab.date), '%Y-%m-%d'),\n" +
                        "		''\n" +
                        "	) AS aitiyTime,\n" +
                        "	IFNULL(\n" +
                        "		DATE_FORMAT(cbs.close_time, '%Y-%m-%d'),\n" +
                        "		''\n" +
                        "	) AS closeTime,\n" +
                        "	IFNULL(re.memo, '') AS memo,\n" +
                        "	IFNULL(re.gzxx, '') AS gzxx,\n" +
                        "	IFNULL(re.cljg, '') AS cljg,\n" +
                        "	IFNULL(re.memo, '') AS eqMemo\n" +
                        "FROM\n" +
                        "	cbs_service cbs\n" +
                        "LEFT JOIN zy_cinema c ON cbs.zy_cinema_id = c.id\n" +
                        "LEFT JOIN cbs_scene_report re ON cbs.id = re.service_id\n" +
                        "LEFT JOIN cbs_equipment_apply eq ON eq.service_id = cbs.id\n" +
                        "LEFT JOIN arrival_of_abnormal ab ON ab.service_id = cbs.id\n" +
                        "WHERE\n" +
                        "	1 = 1\n" +
                        "AND cbs.id = '" + id + "'");
                //附件任务
                List<Map<String, Object>> map1 = systemService.findForJdbc(" SELECT\n" +
                        "\tIFNULL(att.content, '') AS content,\n" +
                        "\tIFNULL(task.`type`, '') AS `status`\n" +
                        "FROM\n" +
                        "\tCBS_ATTACH_TASK att\n" +
                        "LEFT JOIN CBS_SERVICE_TASK_MAP task ON att.id = task.attach_task_id\n" +
                        "WHERE\n" +
                        "\ttask.service_id ='" + id + "' and task.type is not NULL ");
                //设备状况
                List<Map<String, Object>> maps = systemService.findForJdbc("SELECT\n" +
                        "\tIFNULL(ty.type_desc,'') AS typeDesc,\n" +
                        "\tCASE\n" +
                        "WHEN r.jg_reform = '0' THEN\n" +
                        "\t'未光改'\n" +
                        "WHEN r.jg_reform = '1' THEN\n" +
                        "\t'光峰光改'\n" +
                        "WHEN r.jg_reform = '2' THEN\n" +
                        "\t'LP光改'\n" +
                        "ELSE\n" +
                        "\t''\n" +
                        "END AS jgReform,\n" +
                        "IFNULL(r.gypp,'') as gypp,\n" +
                        "IFNULL(r.equipment_run_time,'') as runTime,\n" +
                        "IFNULL(r.wd,'') as wd,\n" +
                        "IFNULL(r.sd,'') as sd,\n" +
                        "IFNULL(r.dy,'') as dy,\n" +
                        "IFNULL(r.lddy,'') as lddy,\n" +
                        "IFNULL(r.gypp,'') as gypp,\n" +
                        "IFNULL(r.gyxh,'') as gyxh,\n" +
                        "IFNULL(r.gy_run_time,'') as gyRunTime,\n" +
                        "IFNULL(r.ddcs,'') as ddcs,\n" +
                        "IFNULL(r.server_type,'') as serverType,\n" +
                        "IFNULL(r.server_sn,'') as serverSn,\n" +
                        "IFNULL(r.server_soft_ver,'') as serverSoftVer,\n" +
                        "IFNULL(r.server_3d_type,'') as threeType,\n" +
                        "IFNULL(r.server_3d_sn,'') as threedSn,\n" +
                        "IFNULL(r.repair_front1,'') as softFront1,\n" +
                        "IFNULL(r.repair_after1,'') as softAfter1,\n" +
                        "IFNULL(r.repair_front2,'') as repair_front2,\n" +
                        "IFNULL(r.repair_after2,'') as repair_after2,\n" +
                        "IFNULL(r.repair_front3,'') as repair_front3,\n" +
                        "IFNULL(r.repair_after3,'') as repair_after3,\n" +
                        "IFNULL(r.repair_front4,'') as repair_front4,\n" +
                        "IFNULL(r.repair_after4,'') as repair_after4\n" +
                        "FROM\n" +
                        "\tcbs_scene_report r\n" +
                        "LEFT JOIN zy_equipment_type ty ON r.equipment_type = ty.id\n" +
                        "WHERE\n" +
                        "\tservice_id = '" + id + "'");
                if (o.size() > 0 && maps.size() > 0) {
                    ajaxJson.setSuccess(true);
                } else {
                    ajaxJson.setSuccess(false);
                }
                map.put("serviceMesg", o);
                map.put("mapList", maps);
                map.put("map1", map1);
//                }


                ajaxJson.setAttributes(map);

            }
        } catch (Exception e) {
            map.put("mapList", 0);
            ajaxJson.setSuccess(false);
            ajaxJson.setAttributes(map);
            e.getMessage();
        }
        return ajaxJson;
    }

    /**
     * @author xiul
     * 2016-8-15 下午8:31:35
     * Description APP - 根据服务单id，获取返件申请
     */
    @ResponseBody
    @RequestMapping(params = "getReturnEquimentByCbsId")
    public AjaxJson getReturnEquimentByCbsId(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = req.getParameter("id");
        List list = new ArrayList();

        Map map1 = new HashMap();
        try {
            if (StringUtil.isNotEmpty(id)) {
                CbsServiceEntity cbsServiceEntity = systemService.getEntity(CbsServiceEntity.class, id);
                List<CbsReturnEquipmentEntity> cbsReturnEquipmentEntity = systemService.findByQueryString("from CbsReturnEquipmentEntity where crCode = '" + cbsServiceEntity.getCode() + "' and  status!='" + StaticValue.RETURN_STATUS_Log_Type_5 + "'");
                if (cbsReturnEquipmentEntity.size() > 0) {
                    for (CbsReturnEquipmentEntity returnEquipment : cbsReturnEquipmentEntity) {
                        Map map = new HashMap();
                        map.put("cbsReturnEquipmentEntity", returnEquipment);
                        List<CbsReturnEquipmentDetailEntity> cbsReturnEquipmentDetailEntities = systemService.findByProperty(CbsReturnEquipmentDetailEntity.class, "returnEquipmentId.id", returnEquipment.getId());
                        map.put("cbsReturnEquipmentDetailEntities", cbsReturnEquipmentDetailEntities);
                        if (cbsReturnEquipmentDetailEntities.size() > 0) {
                        } else {
                            break;
                        }
                        list.add(map);
                    }
                    map1.put("list", list);
                } else {
                    Map map = new HashMap();
                    map.put("cbsReturnEquipmentEntity", null);
                    map.put("cbsReturnEquipmentDetailEntities", null);
                    list.add(map);
                    map1.put("list", list);
                    ajaxJson.setSuccess(false);
                }
            }
        } catch (Exception e) {
            Map map = new HashMap();
            map.put("cbsReturnEquipmentEntity", null);
            map.put("cbsReturnEquipmentDetailEntities", null);
            list.add(map);
            map1.put("list", list);
            ajaxJson.setSuccess(false);
            e.getMessage();
        }
        ajaxJson.setAttributes(map1);
        return ajaxJson;
    }

    /**
     * 根据设备序列号查找机型
     */
    @ResponseBody
    @RequestMapping(params = "getTypeDescBySn")
    public AjaxJson getTypeDescBySn(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        try {
            String sn = request.getParameter("sn");
            String[] split = sn.split(";");
            String typeName = "";
            for (int i = 0; i < split.length; i++) {
                List<Map<String, Object>> zyEquipmentTypeEntitys = systemService.findForJdbc("select t.type_desc as typeDesc from zy_equipment_spare s LEFT JOIN zy_equipment_type t on s.type = t.id where 1=1 and sn = '" + split[i] + "'");
                typeName += zyEquipmentTypeEntitys.get(0).get("typeDesc") + ",";
            }
            System.out.println(typeName);
            String substring = typeName.substring(0, typeName.length() - 1);
            map.put("typeName", substring);
            ajaxJson.setAttributes(map);
            ajaxJson.setSuccess(true);
        } catch (Exception e) {
            map.put("typeName", null);
            ajaxJson.setSuccess(false);
            ajaxJson.setAttributes(map);
            e.getMessage();
        }
        return ajaxJson;
    }

    /**
     * 现场补单app上传照片
     */
    @ResponseBody
    @RequestMapping(params = "appFileUpload", method = RequestMethod.POST)
    public AjaxJson appFileUpload(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map<String, Object> attributes = new HashMap<String, Object>();
        try {

            String compressFileStr = request.getParameter("compressFile");
            String serviceId = request.getParameter("serviceId");
            String ifPlurals = request.getParameter("ifPlurals");
            String ifPlurals2 = request.getParameter("ifPlurals2");
            String ifPlurals3 = request.getParameter("ifPlurals3");
            String ifPlurals4 = request.getParameter("ifPlurals4");
            String imgCaseVal = request.getParameter("imgCaseVal");
            String filePath = StaticValue.UPLOAD_PATH;
            File fileDirectory = new File(filePath);
            if (!fileDirectory.exists() && !fileDirectory.isDirectory()) {
                fileDirectory.mkdirs();
            }
            String suffix = ".jpg";
            String newFileName = UUID.randomUUID().toString().replace("-", "") + suffix;//构建文件名称
            if (StringUtil.isNotEmpty(imgCaseVal)) {
                newFileName = imgCaseVal + getUuid() + suffix;
            }
            String uploadPath = filePath + newFileName;
            File file = new File(uploadPath);
            if (!compressFileStr.equals("")) {
                BASE64Decoder decoder = new BASE64Decoder();
                compressFileStr = compressFileStr.substring(23);
                byte[] bt = decoder.decodeBuffer(compressFileStr);
                for (int i = 0; i < bt.length; i++) {
                    if (bt[i] < 0) {
                        bt[i] += 256;
                    }
                }
                OutputStream opt = new FileOutputStream(file);
                opt.write(bt);
                opt.flush();
                opt.close();
            } else {
                ajaxJson.setMsg("图片为空");
                ajaxJson.setSuccess(false);
            }
            FileBean fileBean = new FileBean();
            fileBean.setFileName(newFileName);
            fileBean.setFilePath(uploadPath);
            fileBean.setFileRealName(file.getName());
            fileBean.setSavePath(file.getAbsolutePath());
            ZyFileLogEntity zyfileLog = new ZyFileLogEntity();
            if (StringUtil.isNotEmpty(serviceId)) {
                zyfileLog.setBusinessKey(serviceId);
            }
            if (StringUtil.isNotEmpty(ifPlurals)) {
                zyfileLog.setBusinessType(ifPlurals);
            }
            if (StringUtil.isNotEmpty(ifPlurals2)) {
                zyfileLog.setBusinessType(ifPlurals2);
                zyfileLog.setBusinessChildType("1");
            }
            if (StringUtil.isNotEmpty(ifPlurals3)) {
                zyfileLog.setBusinessType(ifPlurals3);
                zyfileLog.setBusinessChildType("1");
            }
            if (StringUtil.isNotEmpty(ifPlurals4)) {
                zyfileLog.setBusinessType("I");
                zyfileLog.setBusinessChildType(ifPlurals4);
            }
            zyfileLog.setFilePath(fileBean.getSavePath());
            if ("".equals(imgCaseVal) || imgCaseVal == null) {
                zyfileLog.setOldFileName(fileBean.getFileName());
            } else {
                zyfileLog.setOldFileName(imgCaseVal + suffix);
            }
            zyfileLog.setNewFileName(fileBean.getFileName());
            zyfileLog.setFileType("wgd");
            systemService.save(zyfileLog);
            attributes.put("fileKey", zyfileLog.getId());
            attributes.put("url", fileBean.getFilePath());
            attributes.put("oldFileName", fileBean.getFileRealName());
            attributes.put("name", fileBean.getFileRealName());
            ajaxJson.setAttributes(attributes);
        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.getMessage();
        }
        return ajaxJson;
    }

    /**
     * 现场补单
     *
     * @param cbsServiceEntity
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "addDataByXc")
    public AjaxJson addDataByXc(CbsServiceEntity cbsServiceEntity, HttpServletRequest request) {
        boolean flage = false;
        AjaxJson ajaxJson = new AjaxJson();
        String phone = request.getParameter("phone");
        String type = request.getParameter("type");  //现场补单类型
        String[] errorPhones = request.getParameterValues("errorPhone"); //故障照片，最多10张
        try {
            String split = cbsServiceEntity.getSn().trim();
            CbsServiceEntity cbsServiceEntity1 = new CbsServiceEntity();
            cbsServiceEntity1.setZyCinemaName(cbsServiceEntity.getZyCinemaName());
            cbsServiceEntity1.setContactsName(cbsServiceEntity.getContactsName());
            cbsServiceEntity1.setSn(split);
            cbsServiceEntity1.setSourceType(StaticValue.budan);
            cbsServiceEntity1.setStatus(StaticValue.dcl);
            cbsServiceEntity1.setDescription(cbsServiceEntity.getDescription());
            cbsServiceEntity1.setSpeedStatus(StaticValue.dfp);
            cbsServiceEntity1.setContactsPhone(phone);

            List<Map<String, Object>> results = cbsServiceService.dontService(split); //查找设备序列号是服务器还是设备号
            if (results.size() > 0) {
                if (results.get(0).get("type").equals("Y")) { //服务器
                    ZyEquipmentSpareEntity zyEquipmentSpareList = systemService.findUniqueByProperty(ZyEquipmentSpareEntity.class, "sn", String.valueOf(split)); //设备id
                    cbsServiceEntity1.setZyEquipmentSpareServiceId(zyEquipmentSpareList);
                    cbsServiceEntity1.setRepairEndDate(zyEquipmentSpareList.getRepairEndDate());
                    cbsServiceEntity1.setTypeDec(zyEquipmentSpareList.getType().getTypeDesc());
                }
                if (results.get(0).get("type").equals("N")) {  //设备
                    ZyEquipmentSpareEntity zyEquipmentSpareList = systemService.findUniqueByProperty(ZyEquipmentSpareEntity.class, "sn", String.valueOf(split)); //设备id
                    cbsServiceEntity1.setZyEquipmentSpareId(zyEquipmentSpareList);
                    cbsServiceEntity1.setRepairEndDate(zyEquipmentSpareList.getRepairEndDate());
                    cbsServiceEntity1.setTypeDec(zyEquipmentSpareList.getType().getTypeDesc());
                }
            } else {  //既不是服务器，也不是设备，可能是多个设备号
                flage = true;
            }

            Map m = cbsServiceService.getNo();
            cbsServiceEntity1.setCode(m.get("no").toString());
            cbsServiceService.save(cbsServiceEntity1);

            if (flage && StringUtil.isNotEmpty(split)) {  //添加设备序列号异常
                cbsServiceErrorLogService.doAdd(cbsServiceEntity1, split, "无设备序列号");
            }

            //现场故障照片获取
            if (StringUtil.isNotEmpty(errorPhones) && errorPhones.length > 0) {
                for (String errorPhone : errorPhones) {
                    ZyFileLogEntity zyFileLogEntity1 = zyFileLogServiceI.get(ZyFileLogEntity.class, errorPhone);
                    if (StringUtil.isNotEmpty(zyFileLogEntity1)) {
                        zyFileLogEntity1.setBusinessKey(cbsServiceEntity1.getId());
                        zyFileLogEntity1.setBusinessChildType(StaticValue.Business_File_Type_A);
                        zyFileLogServiceI.save(zyFileLogEntity1);
                    }
                }
            }

            //服务单日志
            TSUser user = ResourceUtil.getSessionUserName();
            cbsServiceLogServiceI.addServiceLog(cbsServiceEntity1, StaticValue.Close_Service_Log_Type_2, "提交现场补单。", null);

            /*******************************************************************************begin*/
            /*服务单受理成功，邮件*/
            String fwtype = "";
            switch (type) {
                case "wx":
                    fwtype = "普通维修";
                    break;
                case "yj":
                    fwtype = "移机";
                    break;
                case "yq":
                    fwtype = "引擎翻新";
                    break;
                case "gg":
                    fwtype = "光管翻新";
                    break;
                case "xc":
                    fwtype = "现场检测";
                    break;
                default:
                    fwtype = "";
                    break;
            }

            // start 181221 Amy 修改收件人为组邮箱 
            logger.info("发送邮件至：HD组");
            ZyEmailEntity eMail = new ZyEmailEntity();
            SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
            String s = "现场补单通知：" + fwtype + "-" + cbsServiceEntity1.getCode() + "-" + cbsServiceEntity1.getSn() + "-" + cbsServiceEntity1.getZyCinemaName() + "-" + sdf.format(new Date()) + "";
            eMail.setEmailSubject(s);
            eMail.setEmailReceiver(StaticValue.COMMON_EMAIL_ADDRESS);
            Map<String, Object> paraMap1 = new HashMap<String, Object>();
            paraMap1.put("name", cbsServiceEntity1.getContactsName());
            paraMap1.put("phone", phone);
            paraMap1.put("description", cbsServiceEntity1.getDescription());
            logger.info("发送邮件");
            SendMailUtil.sendFtlMail(eMail, "mail_xcbd_service.ftl", paraMap1, systemService);

//            List<TSRoleUser> tsRoleUserList = systemService.findHql("from TSRoleUser where TSRole.roleCode='" + StaticValue.CBS_HD_ROLE_CODE + "'");
//            if (tsRoleUserList != null) {
//                for (TSRoleUser tr : tsRoleUserList) {
//                    if (tr.getTSUser() != null && StringUtil.isNotEmpty(tr.getTSUser().getEmail())) {
//                        if (tr.getTSUser().getStatus().equals(Globals.User_Normal)) { //判断Hd用户是否离职
//                            logger.info("发送邮件至：" + tr.getTSUser().getEmail());
//                            ZyEmailEntity eMail = new ZyEmailEntity();
//                            SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
//                            String s = "现场补单通知：" + fwtype + "-" + cbsServiceEntity1.getCode() + "-" + cbsServiceEntity1.getSn() + "-" + cbsServiceEntity1.getZyCinemaName() + "-" + sdf.format(new Date()) + "";
//                            eMail.setEmailSubject(s);
//                            eMail.setEmailReceiver(tr.getTSUser().getEmail());
//                            Map<String, Object> paraMap1 = new HashMap<String, Object>();
//                            paraMap1.put("name", cbsServiceEntity1.getContactsName());
//                            paraMap1.put("phone", phone);
//                            paraMap1.put("description", cbsServiceEntity1.getDescription());
//                            logger.info("发送邮件");
//                            if (StringUtil.isNotEmpty(tr.getTSUser().getEmail())) {
//                                SendMailUtil.sendFtlMail(eMail, "mail_xcbd_service.ftl", paraMap1, systemService);
//                            }
//                        }
//                    }
//                }
//            }
            // end 181221 Amy 修改收件人为组邮箱
            ajaxJson.setSuccess(true);
        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.getMessage();
        }
        return ajaxJson;
    }

    /**
     * 查看维修客户评价
     */
    @RequestMapping(params = "lookServiceEvaluation")
    @ResponseBody
    public AjaxJson lookServiceEvaluation(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        String id = request.getParameter("id");
        try {
            List<Map<String, Object>> cbsInspectionEvaluates = systemService.findForJdbc("SELECT\n" +
                    "\tIFNULL(i.last_evaluate,'') as lastEvalute,\n" +
                    "\tIFNULL(i.service_evaluate,'') as serviceEvaluate,\n" +
                    "\tIFNULL(i.TALK_EVALUATE ,'')as talkEvaluate,\n" +
                    "\tIFNULL(i.TRAIN_EVALUATE,'') as trainEvaluate,\n" +
                    "\tIFNULL(i.SKILL_EVALUATE,'') as skillEvaluate,\n" +
                    "\tIFNULL(i.OPINION,'') as opinion,\n" +
                    "\tIFNULL(DATE_FORMAT(i.create_date,'%Y-%m-%d'),'') as createDate,\n" +
                    "\tIFNULL(s.sn,'') as sn,\n" +
                    "\tIFNULL(s.code,'') as `code`\n" +
                    "FROM\n" +
                    "\tcbs_service s\n" +
                    "LEFT JOIN cbs_inspection_evaluate i ON s.id = i.cbsservice_id\n" +
                    "WHERE\n" +
                    "\t1 = 1\n" +
                    "and s.`status` = '4'\n" +
                    "AND i.cbsservice_id = '" + id + "'");
            if (cbsInspectionEvaluates.size() > 0 && cbsInspectionEvaluates != null) {
                map.put("cbsInspectionEvaluates", cbsInspectionEvaluates);
                ajaxJson.setAttributes(map);
                ajaxJson.setSuccess(true);
            } else {
                ajaxJson.setSuccess(false);
            }
        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.getMessage();
        }
        return ajaxJson;
    }

    /**
     * APP端填写完工单
     *
     * @param
     * @param request
     * @return AjaxJson
     */
    @ResponseBody
    @RequestMapping(params = "writeReport")
    public AjaxJson writeReport(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            String id = request.getParameter("id");
            String type = request.getParameter("type");
            String date = request.getParameter("date");
            CbsServiceEntity cbsService = systemService.getEntity(CbsServiceEntity.class, id);
            if (StringUtil.isNotEmpty(date) && StringUtil.isNotEmpty(id)) {
                JSONObject json = JSONObject.fromObject(date);
                String pfsz = StringUtil.isNotEmpty(json.getString("pfsz")) ? json.getString("pfsz") : "";
                String lwzk = StringUtil.isNotEmpty(json.getString("lwzk")) ? json.getString("lwzk") : "";
                String wd = StringUtil.isNotEmpty(json.getString("wd")) ? json.getString("wd") : "";
                String sd = StringUtil.isNotEmpty(json.getString("sd")) ? json.getString("sd") : "";
                String dy = StringUtil.isNotEmpty(json.getString("dy")) ? json.getString("dy") : "";
                String lddy = StringUtil.isNotEmpty(json.getString("lddy")) ? json.getString("lddy") : "";
                String gzxx = StringUtil.isNotEmpty(json.getString("gzxx")) ? json.getString("gzxx") : "";
                String cljg = StringUtil.isNotEmpty(json.getString("cljg")) ? json.getString("cljg") : "";
                String[] newEquipmentTypes = {};
                if (StringUtil.isNotEmpty(json.getString("newEquipmentType"))) {
                    newEquipmentTypes = new String[json.getString("newEquipmentType").split(",").length];
                    for (int i = 0; i < json.getString("newEquipmentType").split(",").length; i++) {
                        newEquipmentTypes[i] = json.getString("newEquipmentType").split(",")[i];
                    }
                }

                String[] newEquipment = {};
                if (StringUtil.isNotEmpty(json.getString("newEquipment"))) {
                    newEquipment = new String[json.getString("newEquipment").split(",").length];
                    for (int i = 0; i < json.getString("newEquipment").split(",").length; i++) {
                        newEquipment[i] = json.getString("newEquipment").split(",")[i];
                    }
                }

                String[] oldEquipmentType = {};
                if (StringUtil.isNotEmpty(json.getString("oldEquipmentType"))) {
                    oldEquipmentType = new String[json.getString("oldEquipmentType").split(",").length];
                    for (int i = 0; i < json.getString("oldEquipmentType").split(",").length; i++) {
                        oldEquipmentType[i] = json.getString("oldEquipmentType").split(",")[i];
                    }
                }

                String[] oldEquipment = {};
                if (StringUtil.isNotEmpty(json.getString("oldEquipment"))) {
                    oldEquipment = new String[json.getString("oldEquipment").split(",").length];
                    for (int i = 0; i < json.getString("oldEquipment").split(",").length; i++) {
                        oldEquipment[i] = json.getString("oldEquipment").split(",")[i];
                    }
                }

                String[] newEquipmentSn = {};
                if (StringUtil.isNotEmpty(json.getString("newEquipmentSn"))) {
                    newEquipmentSn = new String[json.getString("newEquipmentSn").split(",").length];
                    for (int i = 0; i < json.getString("newEquipmentSn").split(",").length; i++) {
                        newEquipmentSn[i] = json.getString("newEquipmentSn").split(",")[i];
                    }
                }

                String[] newEquipmentCode = {};
                if (StringUtil.isNotEmpty(json.getString("newEquipmentCode"))) {
                    newEquipmentCode = new String[json.getString("newEquipmentCode").split(",").length];
                    for (int i = 0; i < json.getString("newEquipmentCode").split(",").length; i++) {
                        newEquipmentCode[i] = json.getString("newEquipmentCode").split(",")[i];
                    }
                }
                String[] oldEquipmentSn = {};
                if (StringUtil.isNotEmpty(json.getString("oldEquipmentSn"))) {
                    oldEquipmentSn = new String[json.getString("oldEquipmentSn").split(",").length];
                    for (int i = 0; i < json.getString("oldEquipmentSn").split(",").length; i++) {
                        oldEquipmentSn[i] = json.getString("oldEquipmentSn").split(",")[i];
                    }
                }
                String[] oldEquipmentCode = {};
                if (StringUtil.isNotEmpty(json.getString("oldEquipmentCode"))) {
                    oldEquipmentCode = new String[json.getString("oldEquipmentCode").split(",").length];
                    for (int i = 0; i < json.getString("oldEquipmentCode").split(",").length; i++) {
                        oldEquipmentCode[i] = json.getString("oldEquipmentCode").split(",")[i];
                    }
                }

                List<CbsServiceReportEntity> CbsServiceReportList = systemService.findByProperty(CbsServiceReportEntity.class, "serviceId.id", id);

                if (CbsServiceReportList.size() > 0) {
                    systemService.updateBySqlString("update cbs_scene_report set pfsz = '" + pfsz + "'," +
                            "lwzk = '" + Integer.parseInt(StringUtil.isNotEmpty(lwzk) ? lwzk : "0") + "',wd='" + wd + "'," +
                            "sd='" + sd + "',dy='" + dy + "'," +
                            "lddy='" + lddy + "',gzxx='" + gzxx + "',cljg='" + cljg + "',report_category = 1,status = 0" +
                            " where service_id ='" + id + "'");
                    CbsServiceReportEntity cbsServiceReportEntity = CbsServiceReportList.get(0);
                    List<CbsSceneEquipmentUseEntity> cbsSceneEquipmentUseEntity = systemService.findByProperty(CbsSceneEquipmentUseEntity.class, "sceneReportId.id", cbsServiceReportEntity.getId());
                    if (cbsSceneEquipmentUseEntity.size() > 0) {
                        systemService.updateBySqlString("DELETE FROM cbs_scene_equipment_use where SCENE_REPORT_ID = '" + cbsServiceReportEntity.getId() + "'");
                    }
                    if (newEquipmentTypes.length > 0 && StringUtil.isNotEmpty(newEquipmentTypes) && !newEquipmentTypes[0].equals("0")) {
                        for (int i = 0; i < newEquipmentTypes.length; i++) {
                            CbsSceneEquipmentUseEntity cbsSceneEquipmentUseEntitys = new CbsSceneEquipmentUseEntity();

                            /*新备件名称*/
                            if (newEquipmentTypes.length > 0 && StringUtil.isNotEmpty(newEquipmentTypes) && StringUtil.isNotEmpty(newEquipmentTypes[i])) {
                                ZyEquipmentTypeEntity zyEquipmentTypeEntity = new ZyEquipmentTypeEntity();
                                zyEquipmentTypeEntity.setId(newEquipmentTypes[i]);
                                cbsSceneEquipmentUseEntitys.setTypeId(StringUtil.isNotEmpty(zyEquipmentTypeEntity) ? zyEquipmentTypeEntity : null);
                                cbsSceneEquipmentUseEntitys.setTypeDes(StringUtil.isNotEmpty(zyEquipmentTypeEntity) ? zyEquipmentTypeEntity : null);
                            }
                            /*新备件号*/
                            if (newEquipment.length > 0 && StringUtil.isNotEmpty(newEquipment) && StringUtil.isNotEmpty(newEquipment[i])) {
                                ZyEsItemEntity zyEsItemEntity = new ZyEsItemEntity();
                                zyEsItemEntity.setId(newEquipment[i]);
                                cbsSceneEquipmentUseEntitys.setItemId(zyEsItemEntity);
                            }
                            /*故障备件名称*/
                            if (oldEquipmentType.length > 0 && StringUtil.isNotEmpty(oldEquipmentType) && StringUtil.isNotEmpty(oldEquipmentType[i])) {
                                ZyEquipmentTypeEntity zyEquipmentTypeEntity = new ZyEquipmentTypeEntity();
                                zyEquipmentTypeEntity.setId(oldEquipmentType[i]);
                                cbsSceneEquipmentUseEntitys.setOldTypeDes(StringUtil.isNotEmpty(zyEquipmentTypeEntity) ? zyEquipmentTypeEntity : null);
                            }
                            /*旧备件号*/
                            if (oldEquipment.length > 0 && StringUtil.isNotEmpty(oldEquipment) && StringUtil.isNotEmpty(oldEquipment[i])) {
                                ZyEsItemEntity zyEsItemEntity = new ZyEsItemEntity();
                                zyEsItemEntity.setId(oldEquipment[i]);
                                cbsSceneEquipmentUseEntitys.setOldItemId(zyEsItemEntity);
                            }
                            cbsSceneEquipmentUseEntitys.setSceneReportId(cbsServiceReportEntity);
                            if (newEquipmentSn.length > 0 && StringUtil.isNotEmpty(newEquipmentSn) && StringUtil.isNotEmpty(newEquipmentSn[i])) {
                                cbsSceneEquipmentUseEntitys.setSn(StringUtil.isNotEmpty(newEquipmentSn) ? newEquipmentSn[i] : "");
                            }
                            if (newEquipmentCode.length > 0 && StringUtil.isNotEmpty(newEquipmentCode) && StringUtil.isNotEmpty(newEquipmentCode[i])) {
                                cbsSceneEquipmentUseEntitys.setEquipmentErcode(StringUtil.isNotEmpty(newEquipmentCode) ? newEquipmentCode[i] : "");
                            }
                            if (oldEquipmentCode.length > 0 && StringUtil.isNotEmpty(oldEquipmentCode) && StringUtil.isNotEmpty(oldEquipmentCode[i])) {
                                cbsSceneEquipmentUseEntitys.setOldErcode(StringUtil.isNotEmpty(oldEquipmentCode) ? oldEquipmentCode[i] : "");
                            }
                            if (oldEquipmentSn.length > 0 && StringUtil.isNotEmpty(oldEquipmentSn) && StringUtil.isNotEmpty(oldEquipmentSn[i])) {
                                cbsSceneEquipmentUseEntitys.setOldSn(StringUtil.isNotEmpty(oldEquipmentSn) ? oldEquipmentSn[i] : "");
                            }
                            systemService.save(cbsSceneEquipmentUseEntitys);
                        }
                    }

                } else {
                    CbsServiceReportEntity cbsServiceReportEntity = new CbsServiceReportEntity();
                    cbsServiceReportEntity.setPfsz(pfsz);
                    cbsServiceReportEntity.setCljg(cljg);
                    cbsServiceReportEntity.setLwzk(Integer.parseInt(lwzk));
                    cbsServiceReportEntity.setWd(wd);
                    cbsServiceReportEntity.setSd(sd);
                    cbsServiceReportEntity.setDy(dy);
                    cbsServiceReportEntity.setLddy(lddy);
                    cbsServiceReportEntity.setGzxx(gzxx);
                    CbsServiceEntity cbsServiceEntity = new CbsServiceEntity();
                    cbsServiceEntity.setId(id);
                    cbsServiceReportEntity.setServiceId(cbsServiceEntity);
                    cbsServiceReportEntity.setStatus(0);
                    if (StringUtil.isNotEmpty(cbsService.getProvince())) {
                        cbsServiceReportEntity.setSheng(cbsService.getProvince());
                    }
                    if (StringUtil.isNotEmpty(cbsService.getCity())) {
                        cbsServiceReportEntity.setShi(cbsService.getCity());
                    }

                    if (StringUtil.isNotEmpty(cbsService.getZyCinemaId())) {
                        cbsServiceReportEntity.setCinemaName(cbsService.getZyCinemaId().getName());
                    }
                    if (StringUtil.isNotEmpty(cbsService.getAddress())) {
                        cbsServiceReportEntity.setAddress(cbsService.getAddress());
                    }
                    cbsServiceReportEntity.setReportCategory(1);
                    systemService.saveOrUpdate(cbsServiceReportEntity);

                    if (StringUtil.isNotEmpty(newEquipment) && !newEquipment[0].equals("0")) {
                        for (int i = 0; i < newEquipment.length; i++) {
                            CbsSceneEquipmentUseEntity cbsSceneEquipmentUseEntitys = new CbsSceneEquipmentUseEntity();
                            /*新备件名称*/
                            if (newEquipmentTypes.length > 0 && StringUtil.isNotEmpty(newEquipmentTypes) && StringUtil.isNotEmpty(newEquipmentTypes[i])) {
                                ZyEquipmentTypeEntity zyEquipmentTypeEntity = new ZyEquipmentTypeEntity();
                                zyEquipmentTypeEntity.setId(newEquipmentTypes[i]);
                                cbsSceneEquipmentUseEntitys.setTypeId(StringUtil.isNotEmpty(zyEquipmentTypeEntity) ? zyEquipmentTypeEntity : null);
                                cbsSceneEquipmentUseEntitys.setTypeDes(StringUtil.isNotEmpty(zyEquipmentTypeEntity) ? zyEquipmentTypeEntity : null);
                            }
                            /*新备件号*/
                            if (newEquipment.length > 0 && StringUtil.isNotEmpty(newEquipment) && StringUtil.isNotEmpty(newEquipment[i])) {
                                ZyEsItemEntity zyEsItemEntity = new ZyEsItemEntity();
                                zyEsItemEntity.setId(newEquipment[i]);
                                cbsSceneEquipmentUseEntitys.setItemId(zyEsItemEntity);
                            }
                            /*故障备件名称*/
                            if (oldEquipmentType.length > 0 && StringUtil.isNotEmpty(oldEquipmentType) && StringUtil.isNotEmpty(oldEquipmentType[i])) {
                                ZyEquipmentTypeEntity zyEquipmentTypeEntity = new ZyEquipmentTypeEntity();
                                zyEquipmentTypeEntity.setId(oldEquipmentType[i]);
                                cbsSceneEquipmentUseEntitys.setOldTypeDes(StringUtil.isNotEmpty(zyEquipmentTypeEntity) ? zyEquipmentTypeEntity : null);
                            }
                            /*旧备件号*/
                            if (oldEquipment.length > 0 && StringUtil.isNotEmpty(oldEquipment) && StringUtil.isNotEmpty(oldEquipment[i])) {
                                ZyEsItemEntity zyEsItemEntity = new ZyEsItemEntity();
                                zyEsItemEntity.setId(oldEquipment[i]);
                                cbsSceneEquipmentUseEntitys.setOldItemId(zyEsItemEntity);
                            }
                            cbsSceneEquipmentUseEntitys.setSceneReportId(cbsServiceReportEntity);
                            if (newEquipmentSn.length > 0) {
                                cbsSceneEquipmentUseEntitys.setSn(StringUtil.isNotEmpty(newEquipmentSn) ? newEquipmentSn[i] : "");
                            }
                            if (newEquipmentCode.length > 0) {
                                cbsSceneEquipmentUseEntitys.setEquipmentErcode(StringUtil.isNotEmpty(newEquipmentCode) ? newEquipmentCode[i] : "");
                            }
                            if (oldEquipmentCode.length > 0) {
                                cbsSceneEquipmentUseEntitys.setOldErcode(StringUtil.isNotEmpty(oldEquipmentCode) ? oldEquipmentCode[i] : "");
                            }
                            if (oldEquipmentSn.length > 0) {
                                cbsSceneEquipmentUseEntitys.setOldSn(StringUtil.isNotEmpty(oldEquipmentSn) ? oldEquipmentSn[i] : "");
                            }
                            systemService.save(cbsSceneEquipmentUseEntitys);
                        }
                    }
                }

                //提交完工，修改服务单完工时间
                if (type.equals("2")) { //更新完工时间
                    systemService.updateBySqlString("UPDATE cbs_scene_report set finish_time = CURRENT_TIMESTAMP where SERVICE_ID = '" + id + "'");
//                    systemService.updateBySqlString("UPDATE cbs_service SET close_time = CURRENT_TIMESTAMP WHERE id = '" + id + "'");
                    ajaxJson.setSuccess(true);

                    TSUser user = ResourceUtil.getSessionUserName();
                    //服务单日志
                    cbsServiceLogServiceI.addServiceLog(cbsService, StaticValue.Close_Service_Log_Type_2, "在APP中通知完工。", null);


                    //发送通知，短信和微信
                    CbsServiceEntity cbsServiceEntity = systemService.get(CbsServiceEntity.class, id);
                    if (StringUtil.isNotEmpty(cbsServiceEntity)) {
                        if (StringUtil.isNotEmpty(cbsServiceEntity.getContactsPhone())) {
                            //短信
                            Map<String, Object> paraMap = new HashMap<String, Object>();
                            paraMap.put("code", cbsServiceEntity.getCode());
                            SendMessage.sendSMSFTL(cbsServiceEntity.getContactsPhone(), "message_wc_service_business.ftl", paraMap, systemService);
                        }

                        //微信
                        /*发送微信提醒*/
                        List<TSUser> wxUserList = systemService.findHql("from TSUser where mobilePhone='" + cbsServiceEntity.getContactsPhone() + "'");
                        if (wxUserList.size() > 0) {
                            String msContent = "尊敬的客户：您的服务单<" + cbsServiceEntity.getCode() + ">服务已完成。您可在“个人中心-我的服务单”中查看维修详情。【中影巴可客服部】";
                            //调用微信接口发送
                            List<Map<String, String>> list = new ArrayList<>();
                            String openId = wxUserList.get(0).getOpenId();
                            if (StringUtil.isNotEmpty(openId)) {
                                Map<String, String> map = new HashMap<>();
                                map.put("openid", openId);
                                map.put("message", msContent);
                                list.add(map);
                                wxCommonService.sendMsgForWx(list);
                            }
                        }
                    }
                }

            }

        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.getMessage();
        }

        return ajaxJson;
    }

    /**
     * app上传照片
     *
     * @param request
     * @param cbsServiceReportEntity
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "addPhotoToReport")
    public AjaxJson addPhotoToReport(HttpServletRequest request, CbsServiceReportEntity cbsServiceReportEntity) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = request.getParameter("id");
        String type = request.getParameter("type");
        String chooseType = request.getParameter("chooseType");
        String fileIds1 = request.getParameter("fileIds1");
        String fileIds2 = request.getParameter("fileIds2");
        String fileIds3 = request.getParameter("fileIds3");
        String fileIds4 = request.getParameter("fileIds4");
        CbsServiceEntity cbsService = systemService.getEntity(CbsServiceEntity.class, id);
//        //现场照片
//        ZyFileLogEntity zyFileLogEntity = new ZyFileLogEntity();
//        //完工单附件
//        ZyFileLogEntity zyFileLogEntity1 = new ZyFileLogEntity();
//        //延迟证明照片
//        ZyFileLogEntity zyFileLogEntity2 = new ZyFileLogEntity();
//        //整改函
//        ZyFileLogEntity zyFileLogEntity3 = new ZyFileLogEntity();
//
//        zyFileLogEntity.setId(fileIds1);
//        zyFileLogEntity1.setId(fileIds2);
//        zyFileLogEntity2.setId(fileIds3);
//        zyFileLogEntity3.setId(fileIds4);
        try {
            if (StringUtil.isNotEmpty(id)) {
                CbsServiceEntity serviceEntity = systemService.getEntity(CbsServiceEntity.class, id);
                if (type.equals("yq")) {
                    CbsEngineAcceptEntity CbsEngineAcceptEntity1 = systemService.singleResult("from CbsEngineAcceptEntity where serviceId = '" + id + "'");
                    if (CbsEngineAcceptEntity1 == null) {
                        CbsEngineAcceptEntity cbsEngineAcceptEntity = new CbsEngineAcceptEntity();
                        CbsServiceEntity cbsServiceEntity = new CbsServiceEntity();
                        cbsServiceEntity.setId(id);
                        cbsEngineAcceptEntity.setStatus(0);
                        cbsEngineAcceptEntity.setServiceId(id);

                        systemService.save(cbsEngineAcceptEntity);
                        ajaxJson.setSuccess(true);
                    } else {
//                        systemService.updateBySqlString("update cbs_engine_accept_report set finish_file = '" + fileIds2 + "',photo_file = '" + fileIds1 + "' where service_id = '" + id + "'");
                        ajaxJson.setSuccess(true);
                    }
                }
                if (type.equals("gg")) {
                    CbsLightReportEntity cbsLightReportEntity1 = systemService.singleResult("from CbsLightReportEntity where serviceId.id = '" + id + "'");
                    if (cbsLightReportEntity1 == null) {
                        CbsLightReportEntity cbsLightReportEntity = new CbsLightReportEntity();
                        CbsServiceEntity cbsServiceEntity = new CbsServiceEntity();
                        cbsServiceEntity.setId(id);
                        cbsLightReportEntity.setId(id);
                        cbsLightReportEntity.setServiceId(cbsServiceEntity);

                        systemService.save(cbsLightReportEntity);
                        ajaxJson.setSuccess(true);
                    } else {
//                        systemService.updateBySqlString("update cbs_light_report set finish_file = '" + fileIds2 + "',photo_file = '" + fileIds1 + "' where service_id = '" + id + "'");
                        ajaxJson.setSuccess(true);
                    }

                }
                if (type.equals("xc")) {
                    if (chooseType.equals("yqfx")) {
                        CbsEngineSceneCheckReportEntity cbsLightReportEntity1 = systemService.singleResult("from CbsEngineSceneCheckReportEntity where serviceId = '" + id + "'");
                        if (cbsLightReportEntity1 == null) {
                            CbsEngineSceneCheckReportEntity cbsEngineSceneCheckReportEntity = new CbsEngineSceneCheckReportEntity();
                            cbsEngineSceneCheckReportEntity.setStatus("0");
                            cbsEngineSceneCheckReportEntity.setServiceId(id);
                            systemService.save(cbsEngineSceneCheckReportEntity);

                            ajaxJson.setSuccess(true);
                        } else {
//                            systemService.updateBySqlString("update cbs_engine_accept_report set finish_file = '" + fileIds2 + "',photo_file = '" + fileIds1 + "' where service_id = '" + id + "'");
                            ajaxJson.setSuccess(true);
                        }

                    }
                    if (chooseType.equals("qt")) {
                        CbsSceneCheckReportEntity cbsSceneCheckReportEntity1 = systemService.singleResult("from CbsSceneCheckReportEntity where serviceId = '" + id + "'");
                        if (cbsSceneCheckReportEntity1 == null) {
                            CbsSceneCheckReportEntity cbsSceneCheckReportEntity = new CbsSceneCheckReportEntity();
                            cbsSceneCheckReportEntity.setId(id);
                            cbsSceneCheckReportEntity.setServiceId(id);
                            systemService.save(cbsSceneCheckReportEntity);
                            ajaxJson.setSuccess(true);
                        }
                    }
                }
                if ("wx".equals(type)) {
//                    CbsServiceReportEntity cbsServiceReportEntity1 = systemService.getEntity(CbsServiceReportEntity.class, id);
                    CbsServiceReportEntity cbsServiceReportEntity1 = systemService.singleResult("from CbsServiceReportEntity where serviceId.id = '" + id + "'");
                    if (StringUtil.isNotEmpty(cbsServiceReportEntity1)) {

                        ajaxJson.setSuccess(true);
                    } else {
                        if (StringUtil.isNotEmpty(cbsService.getProvince())) {
                            cbsServiceReportEntity.setSheng(cbsService.getProvince());
                        }
                        if (StringUtil.isNotEmpty(cbsService.getCity())) {
                            cbsServiceReportEntity.setShi(cbsService.getCity());
                        }
                        if (StringUtil.isNotEmpty(cbsService.getZyCinemaId())) {
                            cbsServiceReportEntity.setCinemaName(cbsService.getZyCinemaId().getName());
                        }
                        if (StringUtil.isNotEmpty(cbsService.getAddress())) {
                            cbsServiceReportEntity.setAddress(cbsService.getAddress());
                        }
                        cbsServiceReportEntity.setServiceId(serviceEntity);
                        cbsServiceReportEntity.setStatus(0);
                        cbsServiceReportEntity.setReportCategory(1);
                        systemService.save(cbsServiceReportEntity);
                        ajaxJson.setSuccess(true);
                    }
                }

            }
        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.getMessage();
        }
        return ajaxJson;
    }

    /**
     * 填写返件信息查询相关信息,待返件状态
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "getEquipmentToReturn")
    public AjaxJson getEquipmentToReturn(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            String id = request.getParameter("id");
            /*查找服务单code,根据code查找返件信息*/
            String sqlCbs = "SELECT IFNULL(cbs.so, '') AS so, IFNULL(cbs.`code`, '') AS `code`, IFNULL(cbs.sn, '') AS sn, IFNULL(zy.type_desc, '') AS typeDesc FROM cbs_service cbs LEFT JOIN zy_equipment_spare ze ON ze.sn = cbs.sn LEFT JOIN zy_equipment_type zy ON ze.type = zy.id WHERE cbs.id='" + id + "'";
            List<Map<String, Object>> cbsCode = systemService.findForJdbc(sqlCbs);
            if (cbsCode.size() > 0) {
                for (Map<String, Object> stringObjectMap : cbsCode) {
                    String code = stringObjectMap.get("code").toString();  //获取服务单code
                    String so = stringObjectMap.get("so").toString();  //获取服务单so
                    String sn = stringObjectMap.get("sn").toString();  //获取服务单sn
                    String typeDesc = stringObjectMap.get("typeDesc").toString();  //获取服务单typeDesc
                    map.put("code", code);
                    map.put("so", so);
                    map.put("sn", sn);
                    map.put("typeDesc", typeDesc);
                    String sqlReturn = "SELECT rd.id AS detilId,de.type_des AS typeDesc, de.item AS item FROM cbs_return_equipment_detail rd LEFT JOIN cbs_return_equipment re ON re.id = rd.return_equipment_id LEFT JOIN cbs_deliver_equipment de ON de.id = rd.deliver_equuipment_id WHERE re.cr_code = '" + code + "' and re.`status` = " + StaticValue.RETURN_STATUS_Log_Type_1;
                    List<Map<String, Object>> returnEquipments = systemService.findForJdbc(sqlReturn);
                    if (returnEquipments.size() > 0) {
                        map.put("returnEquipments", returnEquipments);
                    } else {
                        ajaxJson.setSuccess(false);
                    }
                }
                ajaxJson.setAttributes(map);
            }
        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.getMessage();
        }
        return ajaxJson;
    }

    /**
     * APP端添加返件
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "addReturnEquipmentData")
    @ResponseBody
    public AjaxJson addReturnEquipmentData(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            String id = request.getParameter("id"); /*服务单id*/
            String[] drid = request.getParameterValues("detilIds");  /*返件明细id*/
            String[] equipmentStatusses = request.getParameterValues("equipmentStatuss"); /*返件状态*/
            String[] memos = request.getParameterValues("memos"); /*备注*/
            String[] returnsn = request.getParameterValues("returnBackSn");  /*返件序列号*/
            String[] returnCode = request.getParameterValues("returnBackCode");  /*返件二维码*/
            /*返件主表*/
            CbsReturnEquipmentEntity cbsReturnEquipmentEntity = null;
            CbsBackEquipmentDetailEntity cbsBackEquipmentDetailEntity = null;
            if (drid.length > 0) {
                for (int v = 0; v < drid.length; v++) {
                    /*返件详情表*/
                    CbsReturnEquipmentDetailEntity cbsReturnEquipmentDetailEntity = systemService.get(CbsReturnEquipmentDetailEntity.class, drid[v]);
                    if (StringUtil.isNotEmpty(cbsReturnEquipmentDetailEntity)) {
                        cbsReturnEquipmentDetailEntity.setReturnEquipmentStatus(equipmentStatusses[v]); //返件的备件状态
                        cbsReturnEquipmentDetailEntity.setSn(returnsn[v]); //序列号
                        cbsReturnEquipmentDetailEntity.setEquipmentErcode(returnCode[v]);
                        cbsReturnEquipmentDetailEntity.setMemo(memos[v]); /*备注*/
                        systemService.saveOrUpdate(cbsReturnEquipmentDetailEntity);
                    }
                    cbsReturnEquipmentEntity = cbsReturnEquipmentDetailEntity.getReturnEquipmentId();
                    cbsReturnEquipmentEntity.setNoticeReturnTime(new Date()); //返件时间
                    cbsReturnEquipmentEntity.setStatus(StaticValue.RETURN_STATUS_Log_Type_2); //修改返件状态为物流待处理

                    List<CbsDelinerEntity> cbsDelinerEntity = systemService.findByProperty(CbsDelinerEntity.class, "code", cbsReturnEquipmentEntity.getDeliverCode());
                    if (StringUtil.isNotEmpty(cbsDelinerEntity) && cbsDelinerEntity.size() > 0) {
                        cbsReturnEquipmentEntity.setName(cbsDelinerEntity.get(0).getUserName());
                        cbsReturnEquipmentEntity.setPhone(cbsDelinerEntity.get(0).getPhone());
                        cbsReturnEquipmentEntity.setAddress(cbsDelinerEntity.get(0).getAddress());
                        cbsReturnEquipmentEntity.setCinemaName(cbsDelinerEntity.get(0).getCinemaName());
                        cbsReturnEquipmentEntity.setLogistics(cbsDelinerEntity.get(0).getReturnLogistics());
                    }
                    systemService.saveOrUpdate(cbsReturnEquipmentEntity);

                    //记录操作日志
                    TSUser user = ResourceUtil.getSessionUserName();
                    CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                    cbsHandleLogEntity.setBusinessId(cbsReturnEquipmentEntity.getId());
                    cbsHandleLogEntity.setLogType(4);
                    cbsHandleLogEntity.setDescription("APP通知返件");
                    cbsHandleLogEntity.setCreateName(user.getRealName());
                    cbsHandleLogEntity.setCreateBy(user.getUserName());
                    systemService.saveOrUpdate(cbsHandleLogEntity);
                }
                ajaxJson.setMsg("返件成功！");
                ajaxJson.setSuccess(true);

                /*通知返件后24小时（该时限可人为设置）后该返件任务状态依然为“返件中”，短信提醒物流商务联系人*/
                if (StringUtil.isNotEmpty(cbsReturnEquipmentEntity)) {
                    String code = "";
                    code = cbsReturnEquipmentEntity.getCrCode(); //服务单code
                    CbsServiceEntity cbsServiceEntity = null;
                    if (StringUtil.isNotEmpty(code)) {
                        List<CbsServiceEntity> cbsServiceEntityList = systemService.findByProperty(CbsServiceEntity.class, "code", code);
                        if (cbsServiceEntityList.size() > 0) {
                            cbsServiceEntity = cbsServiceEntityList.get(0);
                            //根据服务商code ，获取服务商id
                            TSDepart depart = systemService.findUniqueByProperty(TSDepart.class, "orgCode", cbsServiceEntity.getServiceProviderCode());
                            if (StringUtil.isNotEmpty(depart)) {
                                returnEquimentStatus(cbsReturnEquipmentEntity.getId(), depart.getShortname());
                            }
                        }
                    } else {
                        returnEquimentStatus(cbsReturnEquipmentEntity.getId(), "");
                    }
                }

                //获取影院名称
                String cinemaName = "";
                List<CbsDelinerEntity> CbsDelinerEntitys = systemService.findHql("from CbsDelinerEntity where code = '" + cbsReturnEquipmentEntity.getDeliverCode() + "'");
                if (CbsDelinerEntitys.size() > 0) {
                    cinemaName = CbsDelinerEntitys.get(0).getCinemaName();
                }

                /*工程师提交返件后邮件和短信以及APP信息  给物流联系人*/
                if (StringUtil.isNotEmpty(cbsReturnEquipmentEntity)) {
                    String logistics = cbsReturnEquipmentEntity.getLogistics();  //物流单号
                    if (StringUtil.isNotEmpty(logistics)) {
                        String hql = "from TSDepart where departname like '%" + logistics + "%'";
                        TSDepart tsDepart = systemService.singleResult(hql);
                        List<ZyContactsEntity> zyContactsEntities = systemService.findHql("from ZyContactsEntity where belongOrg.id = '" + tsDepart.getId() + "'");
                        if (zyContactsEntities.size() > 0) {

                            for (ZyContactsEntity zyContactsEntity : zyContactsEntities) {
                                //18/5/17   修改取物流联系人为在职的物流联系人
                                if (zyContactsEntity.getState().equals(StaticValue.DIC_ENGINEER_STATE_ONJOB)) {
                                    TSUser tsUser = ResourceUtil.getSessionUserName();//当前人id

                                    /*邮件*/
                                    ZyEmailEntity eMail = new ZyEmailEntity();
                                    SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
                                    String s = "返件通知：<" + cbsReturnEquipmentEntity.getCode() + ">-<" + cbsReturnEquipmentEntity.getCrCode() + ">-<" + cinemaName + ">-<" + cbsReturnEquipmentEntity.getSoCode() + ">-" + sdf.format(new Date()) + "";
                                    eMail.setEmailSubject(s);
                                    eMail.setEmailReceiver(zyContactsEntity.getEmail());
                                    Map<String, Object> paraMap1 = new HashMap<String, Object>();
                                    paraMap1.put("code", cbsReturnEquipmentEntity.getCode());
                                    paraMap1.put("zyContactsName", tsUser.getRealName());
                                    paraMap1.put("phone", tsUser.getMobilePhone());
                                    if (StringUtil.isNotEmpty(zyContactsEntity.getEmail())) {
                                        SendMailUtil.sendFtlMail(eMail, "mail_back_service.ftl", paraMap1, systemService);
                                    }


                                    /*短信*/
                                    Map<String, Object> paraMap = new HashMap<String, Object>();
                                    paraMap.put("code", cbsReturnEquipmentEntity.getCode());
                                    paraMap.put("zyContactsName", tsUser.getRealName());
                                    paraMap.put("phone", tsUser.getMobilePhone());
                                    SendMessage.sendSMSFTL(zyContactsEntity.getCellphone1(), "message_back_service.ftl", paraMap, systemService);

                                }
                            }
                        }
                    }
                }

            } else {
                ajaxJson.setSuccess(false);
                ajaxJson.setMsg("尚未发货，不能返件");
            }
        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.printStackTrace();
        }

        return ajaxJson;
    }

    /**
     * 通知返件后24小时（该时限可人为设置）后该返件任务状态依然为“返件中”，短信提醒物流商务联系人
     *
     * @param id 返件主表id
     */
    public void returnEquimentStatus(final String id, final String contacterName) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                CbsReturnEquipmentEntity cbsReturnEquipmentEntity = systemService.get(CbsReturnEquipmentEntity.class, id);
                if (cbsReturnEquipmentEntity.getStatus().equals(StaticValue.RETURN_STATUS_Log_Type_2)) {
                    String logistics = cbsReturnEquipmentEntity.getLogistics();  //物流单号
                    if (StringUtil.isNotEmpty(logistics)) {
                        String hql = "from TSDepart where orgCode = '" + logistics + "'";
                        TSDepart tsDepart = systemService.singleResult(hql);
                        List<ZyContactsEntity> zyContactsEntities = systemService.findHql("from ZyContactsEntity where belongOrg.id = '" + tsDepart.getId() + "'");
                        if (zyContactsEntities.size() > 0) {
                            for (ZyContactsEntity zyContactsEntity : zyContactsEntities) {
                                //18/5/17   修改取物流联系人为在职的物流联系人
                                if (zyContactsEntity.getState().equals(StaticValue.DIC_ENGINEER_STATE_ONJOB)) {
                                    /*邮件*/
                                    ZyEmailEntity eMail = new ZyEmailEntity();
                                    SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
                                    String s = "返件超时提醒通知：" + cbsReturnEquipmentEntity.getCode() + "-" + cbsReturnEquipmentEntity.getCrCode() + "-" + contacterName + "-" + cbsReturnEquipmentEntity.getSoCode() + "-" + sdf.format(new Date()) + "";
                                    eMail.setEmailSubject(s);
                                    eMail.setEmailReceiver(zyContactsEntity.getEmail());
                                    Map<String, Object> paraMap1 = new HashMap<String, Object>();
                                    paraMap1.put("code", cbsReturnEquipmentEntity.getCode());
                                    if (StringUtil.isNotEmpty(zyContactsEntity.getEmail())) {
                                        SendMailUtil.sendFtlMail(eMail, "mail_back_agin_service.ftl", paraMap1, systemService);
                                    }
                                    /*短信*/
                                    if (StringUtil.isNotEmpty(cbsReturnEquipmentEntity.getCode())) {
                                        SendMessage.sendSMSFTL(zyContactsEntity.getCellphone1(), "message_back_agin_service.ftl", paraMap1, systemService);
                                    }

                                    /*所有CSA*/
                                    List<Map<String, String>> list = getAllCSAUser();
                                    if (list.size() > 0 && StringUtil.isNotEmpty(cbsReturnEquipmentEntity.getCode())) {
                                        for (Map<String, String> stringStringMap : list) {
                                            ZyEmailEntity eMail1 = new ZyEmailEntity();
                                            eMail1.setEmailSubject(s);
                                            eMail1.setEmailReceiver(stringStringMap.get("email"));
                                            SendMailUtil.sendFtlMail(eMail1, "mail_back_agin_service.ftl", paraMap1, systemService);
                                            SendMessage.sendSMSFTL(stringStringMap.get("phone"), "message_back_agin_service.ftl", paraMap1, systemService);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }, StaticValue.returnEquimentTiem);
    }

    //获取所有的CSA角色 联系电话和邮箱
    public List<Map<String, String>> getAllCSAUser() {
        List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
        List<TSRoleUser> tsRoleUserList = systemService.findHql("from TSRoleUser where TSRole.roleCode='" + StaticValue.RULE_CODE_BARCO_CSA_ZB + "'");
        if (tsRoleUserList != null) {
            for (TSRoleUser ru : tsRoleUserList) {
                if (StringUtil.isNotEmpty(ru.getTSUser()) && ru.getTSUser().getStatus().equals(Globals.User_Normal)) {  //18/5/17 增加条件，查询用户状态是正常登陆的用户
                    /*CSA*/
                    Map<String, String> map = new HashMap();
                    map.put("phone", ru.getTSUser().getMobilePhone());
                    map.put("email", ru.getTSUser().getEmail());
                    mapList.add(map);
                }
            }
        }
        return mapList;
    }

    /**
     * 获取上门再次签到时间是否大于1小时，
     *
     * @return
     */
    @RequestMapping(params = "getAppSignTime")
    @ResponseBody
    public AjaxJson getAppSignTime(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        //服务单id
        String ipId = request.getParameter("planIds");
        //获取上门签到时间。如果小于1小时，不允许再次上门签到
        String sql1 = "SELECT now() AS news, HOUR (timediff(now(), date)) AS hours FROM arrival_of_abnormal WHERE service_id = '" + ipId + "'";
        List<Map<String, Object>> list1 = systemService.findForJdbc(sql1);
        if (list1.size() > 0) {
            if (StringUtil.isNotEmpty(list1.get(0).get("hours")) && Integer.parseInt(list1.get(0).get("hours").toString()) < StaticValue.Time) {
                ajaxJson.setSuccess(false);
            }
        }
        return ajaxJson;
    }

    /**
     * 上门签到时，获取页面基本信息
     *
     * @return
     */
    @RequestMapping(params = "appEgSignInDetial")
    @ResponseBody
    public AjaxJson appEgSignInDetial(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        //服务单id
        String ipId = request.getParameter("planIds");
        String SQL = "SELECT cbs.id AS id, IFNULL(cbs.`code`,'') AS `code`, IFNULL(cbs.sn,'') AS sn, IFNULL(MAX(a.num+1), 1) AS doornumber, IFNULL( DATE_FORMAT( cbs.order_time_agin, '%Y-%m-%d' ), IFNULL( DATE_FORMAT( cbs.order_time, '%Y-%m-%d' ), '' )) AS ordertime, IFNULL(DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s'),'') AS actualtime, IFNULL(eq.type_desc, '') AS typedesc FROM cbs_service cbs LEFT JOIN arrival_of_abnormal a ON a.service_id = cbs.id LEFT JOIN zy_equipment_spare s ON s.sn = cbs.sn LEFT JOIN zy_equipment_type eq ON s.type = eq.id WHERE cbs.id =  '" + ipId + "'";
        List<Map<String, Object>> list = systemService.findForJdbc(SQL);
        if (list.size() > 0) {
            ajaxJson.setAttributes(list.get(0));
            ajaxJson.setSuccess(true);
        }
        return ajaxJson;
    }


    /**
     * APP 确认上门签到
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "doAddServiceBjError")
    @ResponseBody
    public AjaxJson doAddServiceBjError(HttpServletRequest request) throws ParseException {
        AjaxJson ajaxJson = new AjaxJson();

        String actualtime = request.getParameter("actualtime"); //实际上门时间
        String doornumber = request.getParameter("doornumber"); //上门次数
        String radio1 = request.getParameter("radio1");
        String radio2 = request.getParameter("radio2");
        String radio3 = request.getParameter("radio3");
        String NotNormal = request.getParameter("NotNormal");
        String ipId = request.getParameter("ipId");
        String errorPhone = request.getParameter("errorPhone"); //故障照片id，以逗号分隔
        if (StringUtil.isNotEmpty(ipId)) {

            CbsServiceEntity cbsServiceEntity = systemService.getEntity(CbsServiceEntity.class, ipId);
            cbsServiceEntity.setSpeedStatus(StaticValue.gcsssz);
            systemService.saveOrUpdate(cbsServiceEntity);
            ArrivalofabnormalEntity arrivalofabnormal = new ArrivalofabnormalEntity();

            if (radio1.equals("1")) {
                arrivalofabnormal.setSpareIsContain(Integer.parseInt(radio1));
            } else {
                arrivalofabnormal.setSpareIsContain(0);
            }
            if (radio2.equals("1")) {
                arrivalofabnormal.setIsIntact(Integer.parseInt(radio2));
            } else {
                arrivalofabnormal.setIsIntact(0);
            }
            if (radio3.equals("1")) {
                arrivalofabnormal.setIsNormal(Integer.parseInt(radio3));
            } else {
                arrivalofabnormal.setIsNormal(0);
            }
            arrivalofabnormal.setNum(Integer.parseInt(doornumber));
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            arrivalofabnormal.setDate(sd.parse(actualtime));
            arrivalofabnormal.setIsContent(NotNormal);
            arrivalofabnormal.setServiceId(cbsServiceEntity);
            systemService.saveOrUpdate(arrivalofabnormal);

            if (StringUtil.isNotEmpty(errorPhone)) {
                for (String s : errorPhone.split(",")) {
                    if (StringUtil.isNotEmpty(s)) {
                        ZyFileLogEntity zyFileLogEntity = systemService.get(ZyFileLogEntity.class, s);
                        zyFileLogEntity.setBusinessKey(arrivalofabnormal.getId());
                        systemService.saveOrUpdate(zyFileLogEntity);
                    }
                }
            }

            TSUser user = ResourceUtil.getSessionUserName();
            //服务单日志
            cbsServiceLogServiceI.addServiceLog(cbsServiceEntity, StaticValue.Close_Service_Log_Type_2, user.getRealName() + "上门签到成功。", null);

        }
        return ajaxJson;
    }

    /**
     * 备件发货单详情
     *
     * @return
     */
    @RequestMapping(params = "getDeliverDetailByCbsId")
    @ResponseBody
    public AjaxJson getDeliverDetailByCbsId(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = request.getParameter("deliverId");//备件申请明细id
        Map<String, Object> map = new HashMap<>();
        //服务单信息
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("SELECT\n" +
                "\tIFNULL(d.sn,'') AS sn,\n" +
                "\tIFNULL(cbs.`code`,'') AS `code`,\n" +
                "\tIFNULL(cbs.description,'') AS description,\n" +
                "\tCASE a.zt\n" +
                "WHEN '1' THEN\n" +
                "\t'是'\n" +
                "WHEN '2' THEN\n" +
                "\t'否'\n" +
                "END AS zt,\n" +
                " IFNULL(a.user_name,'') AS `name`,\n" +
                " IFNULL(a.phone,'') AS phone,\n" +
                " CONCAT( IFNULL(t.territoryname, ''), IFNULL(t1.territoryname, '') ,IFNULL(a.address, '')) AS address,\n" +
                " IFNULL(a.cinema_name,'') AS cinemaname,\n" +
                " IFNULL(a.apply_reason,'') AS apply_reason,\n" +
                " IFNULL(a.create_date,'') AS date,\n" +
                " IFNULL(cbs.so,'') AS so,\n" +
                " CASE a.`status`\n" +
                "WHEN 1 THEN\n" +
                "\t'待审批'\n" +
                "WHEN 2 THEN\n" +
                "\t'审批通过'\n" +
                "else \n" +
                "\t'未通过'\n" +
                "end `status`,\n" +
                "IFNULL(a.memo,'') as reasion,\n" +
                "IFNULL(a.update_date,'') as updatedate,\n" +
                "IFNULL(a.update_name,'') as realname\n" +
                "FROM\n" +
                "\tcbs_equipment_apply_detail d\n" +
                "LEFT JOIN cbs_equipment_apply a ON a.id = d.apply_id\n" +
                "LEFT JOIN cbs_service cbs ON cbs.id = a.service_id\n" +
                "LEFT JOIN CBS_DELIVER_EQUIPMENT deli ON deli.equipment_apply_detail_id = d.id\n" +
                "LEFT JOIN CBS_DELIVER cd ON cd.id = deli.deliver_id\n" +
                "LEFT JOIN t_s_base_user u on u.id = a.approve_user\n" +
                "LEFT JOIN t_s_territory t on t.id = a.sheng\n" +
                "LEFT JOIN t_s_territory t1 on t1.id = a.shi\n" +
                " WHERE d.id='" + id + "'");
        //服务单和备件信息
        List<Map<String, Object>> list = systemService.findForJdbc(stringBuffer.toString());
        if (list.size() > 0) {
            map.put("list", list.get(0));
        }
        //发货信息
        String sql = "SELECT\n" +
                "\td1.id AS id\n" +
                "FROM\n" +
                "\tcbs_deliver d1\n" +
                "\tLEFT JOIN cbs_deliver_equipment d ON d1.id = d.DELIVER_ID\n" +
                "\tLEFT JOIN cbs_equipment_apply_detail e ON e.id = d.equipment_apply_detail_id\n" +
                "\tWHERE\n" +
                "\te.id = '" + id + "'";
        List<Map<String, Object>> list1 = systemService.findForJdbc(sql);
        if (list1.size() > 0) {
            StringBuffer sb = new StringBuffer();
            sb.append("SELECT\n" +
                    "\tCASE `status`\n" +
                    "WHEN '1' THEN\n" +
                    "\t'CSA待发货'\n" +
                    "WHEN '2' THEN\n" +
                    "\t'CSA已发货'\n" +
                    "WHEN '3' THEN\n" +
                    "\t'CSA取消发货'\n" +
                    "WHEN '4' THEN\n" +
                    "\t\t\t'欠货中'\n" +
                    "\t\tWHEN '5' THEN\n" +
                    "\t\t\t'物流待发货'\n" +
                    "\t\tWHEN '6' THEN\n" +
                    "\t\t\t'物流已发货'\n" +
                    "\t\tWHEN '7' THEN\n" +
                    "\t\t\t'签收' else ''\n" +
                    "END AS status,\n" +
                    " IFNULL(expecttime,'') AS expecttime,\n" +
                    " IFNULL(`code`,'') AS `code`,\n" +
                    " IFNULL(deliver_logistics,'') AS deliverlogistics\n" +
                    "FROM\n" +
                    "\tcbs_deliver\n" +
                    "WHERE\n" +
                    "\tid = '" + list1.get(0).get("id").toString() + "'");
            List list2 = systemService.findForJdbc(sb.toString());
            if (list2.size() > 0) {
                map.put("cbsDeliner", list2.get(0));
            }
            String sql1 = "SELECT\n" +
                    "\tIFNULL(e.type_des,'') AS typedesc,\n" +
                    "\tIFNULL(e.item,'') AS item,\n" +
                    "\tCASE e.apply_layer\n" +
                    "WHEN '1' THEN\n" +
                    "\t'低'\n" +
                    "WHEN '2' THEN\n" +
                    "\t'中'\n" +
                    "WHEN '3' THEN\n" +
                    "\t'高'\n" +
                    "WHEN '4' THEN\n" +
                    "\t'加急' else ''\n" +
                    "end as applylayer\n" +
                    "FROM\n" +
                    "\tcbs_deliver_equipment e\n" +
                    " WHERE e.DELIVER_ID='" + list1.get(0).get("id").toString() + "'";
            List list3 = systemService.findForJdbc(sql1.toString());
            if (list3.size() > 0) {
                map.put("cbsDeliverEquipment", list3);
            }
        }
        ajaxJson.setAttributes(map);
        return ajaxJson;
    }

    @ResponseBody
    @RequestMapping(params = "getEquipmentSpace")
    public AjaxJson getEquipmentSpace(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        try {
            String id = request.getParameter("id");
            List<Map<String, Object>> cbsEquipments = systemService.findForJdbc("SELECT\n" +
                    "\tIFNULL(cbs.`code`,'') as `code`,\n" +
                    "\tIFNULL(cbs.sn,'') as sn,\n" +
                    "\tIFNULL(zyp.sn,'') as zypSn,\n" +
                    "\tIFNULL(type.type_desc,'') as typeDesc,IFNULL(cbs.description,'') as description\n" +
                    "FROM\n" +
                    "\tcbs_service cbs\n" +
                    "LEFT JOIN zy_equipment_spare zyp ON cbs.sn = zyp.sn\n" +
                    "LEFT JOIN zy_equipment_type type on zyp.type = type.id\n" +
                    "WHERE\n" +
                    "\tcbs.id = '" + id + "'");
            if (cbsEquipments.size() > 0) {
                map.put("cbsEquipments", cbsEquipments);
                ajaxJson.setAttributes(map);
                ajaxJson.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.getMessage();
        }
        return ajaxJson;
    }

    /**
     * 获取备件类型
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "getEquipmentType")
    public AjaxJson getEquipmentType(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        List<Map<String, Object>> maps = new ArrayList<>();
        try {
            ZyEquipmentTypeEntity zyEquipmentTypeEntity = systemService.singleResult(" from ZyEquipmentTypeEntity where typeDesc = '备件'");
            List<Map<String, Object>> zyequipmentTypes = systemService.findForJdbc("select id as id,type_desc as typeDesc from zy_equipment_type where parent_id = '" + zyEquipmentTypeEntity.getId() + "'");
            if (zyequipmentTypes.size() > 0) {
                for (Map<String, Object> zyequipmentType : zyequipmentTypes) {
                    List<Map<String, Object>> zyequipment = systemService.findForJdbc("select id as id,type_desc as typeDesc from zy_equipment_type where parent_id = '" + zyequipmentType.get("id") + "'");
                    maps.addAll(zyequipment);
                }
                //未知备件
                List<Map<String, Object>> types = systemService.findForJdbc("SELECT id AS id, type_desc AS typeDesc FROM zy_equipment_type WHERE type_desc = '未知备件'");
                if (types.size() > 0) {
                    maps.addAll(types);
                }
                map.put("zyequipmentTypes", maps);
                ajaxJson.setAttributes(map);
                ajaxJson.setSuccess(true);
            }

        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.getMessage();
        }
        return ajaxJson;
    }

    /**
     * 根据备件机型名称查询当前机型
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "getTypeDescByTypeDesc")
    public AjaxJson getTypeDescByTypeDesc(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        try {
            String type = request.getParameter("type");
            ZyEquipmentTypeEntity zyEquipmentTypeEntity = systemService.singleResult("from ZyEquipmentTypeEntity where typeDesc = '" + type + "'");
            List<Map<String, Object>> typeDescs = systemService.findForJdbc("select id as id,type_desc as typeDesc from zy_equipment_type where parent_id = '" + zyEquipmentTypeEntity.getEquipmentType().getId() + "'");

            if (typeDescs.size() > 0) {
                map.put("typeDescs", typeDescs);
                ajaxJson.setAttributes(map);
                ajaxJson.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.getMessage();
        }

        return ajaxJson;
    }

    /**
     * 根据备件类型获取备件号
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "getItembyType")
    public AjaxJson getItembyType(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        try {
            List<ZyEsItemEntity> zyEsItemEntityList = new ArrayList<>();
            String typeId = request.getParameter("typeId"); /*备件类型id*/
            String sbjx = request.getParameter("sbjx");  //设备机型id
            if (!sbjx.equals("-- 请选择 --")) {
                zyEsItemEntityList = zyEsItemServiceI.findHql("from ZyEsItemEntity where type.id='" + typeId + "' and scope like'%" + sbjx + "%'");
            } else {
                zyEsItemEntityList = zyEsItemServiceI.findHql("from ZyEsItemEntity where type.id='" + typeId + "'");
            }
            if (zyEsItemEntityList.size() > 0) {
                map.put("zyEsItemEntityList", zyEsItemEntityList);
                ajaxJson.setAttributes(map);
                ajaxJson.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.getMessage();
        }

        return ajaxJson;
    }

    /**
     * APP添加备件申请
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "addData")
    @ResponseBody
    public AjaxJson addData(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        TSUser user = ResourceUtil.getSessionUserName();
        try {
            String id = request.getParameter("id");
            CbsServiceEntity cbsServiceEntity = systemService.getEntity(CbsServiceEntity.class, id);
            String[] bjlxs = request.getParameterValues("bjlxs");
            String[] bjlxvalues = request.getParameterValues("bjlxvalue"); //备件类型id
            String[] bjhs = request.getParameterValues("bjhs");
            String[] bjhvalues = request.getParameterValues("bjhvalue");  //备件号id
            String[] nums = request.getParameterValues("nums");
            String[] applers = request.getParameterValues("applers");
            String sn = request.getParameter("sn");
            String reason = request.getParameter("reason");
            String name = request.getParameter("name");
            String phone = request.getParameter("phone");
            String address = request.getParameter("address");
            String addressDetil = request.getParameter("addressDetil");
            String ztWarouse = request.getParameter("ztWarouse");
            String applerStatement = request.getParameter("applerStatement");
            String[] bjlxXlhs = request.getParameterValues("bjlxXlhs");
            String[] bjlxTexts = request.getParameterValues("bjlxTexts");
            String[] equipmentSns = request.getParameterValues("equipmentSns");
            String[] equipmentCodes = request.getParameterValues("equipmentCodes");
            String[] imgShow = request.getParameterValues("imgShow"); //备件照片
            String zt = request.getParameter("zt");
            String type = request.getParameter("type");
            String cinemaName = request.getParameter("cinemaName");
            String[] split = address.split(" ");

            String Spareid = request.getParameter("Spareid"); //修改备件的备件id
            CbsEquipmentApplyEntity cbsEquipmentApplyEntity = null;
            if (StringUtil.isNotEmpty(Spareid)) {
            	cbsEquipmentApplyEntity = systemService.getEntity(CbsEquipmentApplyEntity.class, Spareid);
            	// 判断是否已审批
                if (cbsEquipmentApplyEntity == null || cbsEquipmentApplyEntity.getStatus() != 1) {
                    ajaxJson.setSuccess(false);
                    ajaxJson.setMsg("备件申请状态已更新，请刷新页面");
                    return ajaxJson;
                }
                systemService.updateBySqlString("update CBS_EQUIPMENT_APPLY set memo='工程师修改备件申请',status='3',update_date = NOW(),update_by='" + user.getUserName() + "',update_name='" + user.getRealName() + "' where id='" + Spareid + "'");
            }
            TSTerritory tsTerritory = null;
            TSTerritory tsTerritory1 = null;
            if (split.length > 0) {
                //发货省
                if ("重庆".equals(split[0])) {
                    split[0] = "重庆市";
                }
                if ("宁夏".equals(split[0])) {
                    split[0] = "宁夏省";
                }
                if ("西藏".equals(split[0])) {
                    split[0] = "西藏自治区";
                }
                if ("新疆".equals(split[0])) {
                    split[0] = "新疆维吾尔自治区";
                }
                if ("广西壮族".equals(split[0])) {
                    split[0] = "广西省";
                }
                if ("内蒙古".equals(split[0])) {
                    split[0] = "内蒙古自治区";
                }
                tsTerritory = systemService.singleResult("from TSTerritory where territoryName = '" + split[0] + "' and territoryLevel = 1");
            }
            if (split.length > 1) {
                if ("重庆".equals(split[1])) {
                    split[1] = "重庆市";
                }
                //发货市
                tsTerritory1 = systemService.singleResult("from TSTerritory where territoryName = '" + split[1] + "' and territoryLevel = 2");
            }
            if (StringUtil.isNotEmpty(cbsEquipmentApplyEntity) && cbsEquipmentApplyEntity.getJudge() == 2) {

                cbsEquipmentApplyEntity.setSheng(tsTerritory);
                cbsEquipmentApplyEntity.setShi(tsTerritory1);
                cbsEquipmentApplyEntity.setZt(Integer.valueOf(zt));
                cbsEquipmentApplyEntity.setServiceId(id);
                cbsEquipmentApplyEntity.setSn(sn);
                cbsEquipmentApplyEntity.setEquipmentType(type);
                cbsEquipmentApplyEntity.setAddress(addressDetil);
                cbsEquipmentApplyEntity.setStatus(1);
                cbsEquipmentApplyEntity.setUserName(name);
                cbsEquipmentApplyEntity.setPhone(phone);
                cbsEquipmentApplyEntity.setCinemaName(cinemaName);
                cbsEquipmentApplyEntity.setWarehouseId(ztWarouse);
                cbsEquipmentApplyEntity.setApplyReason(reason);
                if (cbsServiceEntity.getSr() != null) {
                    cbsEquipmentApplyEntity.setSrCode(cbsServiceEntity.getSr());
                }
                systemService.saveOrUpdate(cbsEquipmentApplyEntity);
                //删除原有的备件详情
                List<CbsEquipmentApplyDetailEntity> cbsEquipmentApplyDetailEntityList = systemService.findHql("from CbsEquipmentApplyDetailEntity where applyId.id='" + cbsEquipmentApplyEntity.getId() + "'");
                for (CbsEquipmentApplyDetailEntity c : cbsEquipmentApplyDetailEntityList) {
                    systemService.delete(c);
                }

                /*修改备件申请日志*/
                CbsHandleLogEntity cbsHandleLog = new CbsHandleLogEntity();
                cbsHandleLog.setBusinessId(cbsEquipmentApplyEntity.getId());
                cbsHandleLog.setLogType(1);
                cbsHandleLog.setDescription("APP端修改了备件申请");
                systemService.save(cbsHandleLog);

                //添加备件详情
                if (bjlxs != null) {
                    for (int i = 0; i < bjlxs.length; i++) {
                        CbsEquipmentApplyDetailEntity cbsEquipmentApplyDetailEntity = new CbsEquipmentApplyDetailEntity();
                        cbsEquipmentApplyDetailEntity.setApplyId(cbsEquipmentApplyEntity);
                        cbsEquipmentApplyDetailEntity.setCode(cbsEquipmentApplyEntity.getCode());

                        if (!"未知备件".equals(bjlxs[i])) {
                            ZyEsItemEntity zyEsItemEntity = systemService.singleResult("from ZyEsItemEntity where item = '" + bjhs[i].trim() + "'");
                            cbsEquipmentApplyDetailEntity.setItemId(zyEsItemEntity);
                            if (StringUtil.isNotEmpty(zyEsItemEntity)) {
                                //备件号id
                                cbsEquipmentApplyDetailEntity.setItemId(zyEsItemEntity);
                                cbsEquipmentApplyDetailEntity.setItem(bjhs[i]);

                                ZyEquipmentTypeEntity zyEquipmentTypeEntity = zyEsItemEntity.getType();
                                //备件类型id
                                cbsEquipmentApplyDetailEntity.setTypeId(zyEquipmentTypeEntity);
                                cbsEquipmentApplyDetailEntity.setTypeDes(bjlxs[i]);
                            }

                        } else {
                            ZyEquipmentTypeEntity zyEquipmentTypeEntity = systemService.singleResult("from ZyEquipmentTypeEntity where typeDesc = '" + bjlxs[i] + "'");
                            //备件类型id
                            cbsEquipmentApplyDetailEntity.setTypeId(zyEquipmentTypeEntity);
                            cbsEquipmentApplyDetailEntity.setTypeDes(bjlxs[i]);
                            cbsEquipmentApplyDetailEntity.setItemDesc(bjhs[i]);
                            cbsEquipmentApplyDetailEntity.setItem(bjhs[i]);
                            //通过备件号反查ID和Type并保存
                            List<ZyEsItemEntity> itemf = systemService.findHql("from ZyEsItemEntity where item='" + bjhs[i].trim() + "'");
                            if (itemf.size() > 0) {
                                cbsEquipmentApplyDetailEntity.setItemId(itemf.get(0));
                                cbsEquipmentApplyDetailEntity.setItemDesc(itemf.get(0).getItemDesc());
                                cbsEquipmentApplyDetailEntity.setItem(itemf.get(0).getItem());
                                ZyEquipmentTypeEntity Typef = itemf.get(0).getType();
                                if (Typef != null) {
                                    cbsEquipmentApplyDetailEntity.setTypeId(Typef);
                                    cbsEquipmentApplyDetailEntity.setTypeDes(Typef.getTypeDesc());
                                }
                            }
                        }


                        cbsEquipmentApplyDetailEntity.setSn(sn);
                        cbsEquipmentApplyDetailEntity.setTotal(Integer.valueOf(nums[i]));


                        int applyer = 0;
                        if (applers[i].equals("低")) {
                            applyer = 1;
                        } else if (applers[i].equals("中")) {
                            applyer = 2;
                        } else if (applers[i].equals("高")) {
                            applyer = 3;
                        } else if (applers[i].equals("加急")) {
                            applyer = 4;
                        }
                        cbsEquipmentApplyDetailEntity.setApplyLayer(applyer);
                        cbsEquipmentApplyDetailEntity.setMemo(applerStatement);
                        systemService.saveOrUpdate(cbsEquipmentApplyDetailEntity);
                    }
                }

                String sql = "select record_id  from cbs_equipment_apply where id='" + cbsEquipmentApplyEntity.getId() + "' ORDER BY create_date desc LIMIT 0,1";
                List<String> listbySql2 = systemService.findListbySql(sql);
                /*备件申请审批邮件提醒*/
                sendToCSA(cbsServiceEntity, listbySql2, user);

            } else {

                //添加备件
                CbsEquipmentApplyEntity cbsEquipmentApply = new CbsEquipmentApplyEntity();
                Date date = new Date();
                DateFormat format = new SimpleDateFormat("yyyyMMdd");
                String time = format.format(date);
                StringBuffer buffer = new StringBuffer();
                buffer.append("CO");
                buffer.append(time);
                List<Object[]> cbsEquipmentApplyList = systemService.findListbySql("select * from cbs_equipment_apply where to_days(create_date) = to_days(now()) ORDER BY record_id desc;");
                if (cbsEquipmentApplyList.size() == 0) {
                    buffer.append("001");
                    String s = buffer.toString();
                    cbsEquipmentApply.setRecordId(s);
                    cbsEquipmentApply.setSheng(tsTerritory);
                    cbsEquipmentApply.setShi(tsTerritory1);
                    cbsEquipmentApply.setZt(Integer.valueOf(zt));
                    cbsEquipmentApply.setServiceId(id);
                    cbsEquipmentApply.setSn(sn);
                    cbsEquipmentApply.setEquipmentType(type);
                    cbsEquipmentApply.setAddress(addressDetil);
                    cbsEquipmentApply.setStatus(1);
                    cbsEquipmentApply.setUserName(name);
                    cbsEquipmentApply.setPhone(phone);
                    cbsEquipmentApply.setJudge(2); //工程师自己添加的备件
                    cbsEquipmentApply.setCinemaName(cinemaName);
                    cbsEquipmentApply.setWarehouseId(ztWarouse);
                    cbsEquipmentApply.setApplyReason(reason);
                    if (cbsServiceEntity.getSr() != null) {
                        cbsEquipmentApply.setSrCode(cbsServiceEntity.getSr());
                    }
                    systemService.saveOrUpdate(cbsEquipmentApply);
                } else {
                    String o = (String) cbsEquipmentApplyList.get(0)[1];
                    String s = o.substring(10, 13);
                    int i = Integer.parseInt(s);
                    i++;
                    if (i <= 9) {
                        buffer.append("00" + i);
                    } else if (i >= 10 && i < 100) {
                        buffer.append("0" + i);
                    } else {
                        buffer.append("" + i);
                    }
                    String string = buffer.toString();
                    cbsEquipmentApply.setServiceId(id);
                    cbsEquipmentApply.setSn(sn);
                    cbsEquipmentApply.setUserName(name);
                    cbsEquipmentApply.setPhone(phone);
                    cbsEquipmentApply.setCinemaName(cinemaName);
                    cbsEquipmentApply.setRecordId(string);
                    cbsEquipmentApply.setSheng(tsTerritory);
                    cbsEquipmentApply.setShi(tsTerritory1);
                    cbsEquipmentApply.setAddress(addressDetil);
                    cbsEquipmentApply.setEquipmentType(type);
                    cbsEquipmentApply.setJudge(2); //工程师自己添加的备件
                    cbsEquipmentApply.setWarehouseId(ztWarouse);
                    cbsEquipmentApply.setApplyReason(reason);
                    cbsEquipmentApply.setZt(Integer.valueOf(zt));
                    cbsEquipmentApply.setStatus(1);
                    if (cbsServiceEntity.getSr() != null) {
                        cbsEquipmentApply.setSrCode(cbsServiceEntity.getSr());
                    }
                    systemService.saveOrUpdate(cbsEquipmentApply);
                }

                //备件申请上传的照片保存
                if (StringUtil.isNotEmpty(imgShow) && imgShow.length > 0) {
                    for (int i = 0; i < imgShow.length; i++) {
                        if (StringUtil.isNotEmpty(imgShow[i])) {
                            ZyFileLogEntity zyFileLog = systemService.get(ZyFileLogEntity.class, imgShow[i]);
                            zyFileLog.setBusinessKey(cbsEquipmentApply.getId());
                        }
                    }
                }

                /*创建备件申请日志*/
                CbsHandleLogEntity cbsHandleLog = new CbsHandleLogEntity();
                cbsHandleLog.setBusinessId(cbsEquipmentApply.getId());
                cbsHandleLog.setLogType(1);
                cbsHandleLog.setDescription("APP创建了备件申请");
                systemService.save(cbsHandleLog);

                if (bjlxs != null) {
                    for (int i = 0; i < bjlxs.length; i++) {
                        CbsEquipmentApplyDetailEntity cbsEquipmentApplyDetailEntity = new CbsEquipmentApplyDetailEntity();
                        cbsEquipmentApplyDetailEntity.setApplyId(cbsEquipmentApply);
                        cbsEquipmentApplyDetailEntity.setCode(cbsEquipmentApply.getCode());

                        if (!"未知备件".equals(bjlxs[i])) {
                            ZyEsItemEntity zyEsItemEntity = systemService.singleResult("from ZyEsItemEntity where item = '" + bjhs[i].trim() + "'");
                            cbsEquipmentApplyDetailEntity.setItemId(zyEsItemEntity);
                            if (StringUtil.isNotEmpty(zyEsItemEntity)) {
                                //备件号id
                                cbsEquipmentApplyDetailEntity.setItemId(zyEsItemEntity);
                                cbsEquipmentApplyDetailEntity.setItem(bjhs[i]);

                                ZyEquipmentTypeEntity zyEquipmentTypeEntity = zyEsItemEntity.getType();
                                //备件类型id
                                cbsEquipmentApplyDetailEntity.setTypeId(zyEquipmentTypeEntity);
                                cbsEquipmentApplyDetailEntity.setTypeDes(bjlxs[i]);
                            }

                        } else {
                            ZyEquipmentTypeEntity zyEquipmentTypeEntity = systemService.singleResult("from ZyEquipmentTypeEntity where typeDesc = '" + bjlxs[i] + "'");
                            //备件类型id
                            cbsEquipmentApplyDetailEntity.setTypeId(zyEquipmentTypeEntity);
                            cbsEquipmentApplyDetailEntity.setTypeDes(bjlxs[i]);
                            cbsEquipmentApplyDetailEntity.setItemDesc(bjhs[i]);
                            cbsEquipmentApplyDetailEntity.setItem(bjhs[i]);
                            //通过备件号反查ID和Type并保存
                            List<ZyEsItemEntity> itemf = systemService.findHql("from ZyEsItemEntity where item='" + bjhs[i].trim() + "'");
                            if (itemf.size() > 0) {
                                cbsEquipmentApplyDetailEntity.setItemId(itemf.get(0));
                                cbsEquipmentApplyDetailEntity.setItemDesc(itemf.get(0).getItemDesc());
                                cbsEquipmentApplyDetailEntity.setItem(itemf.get(0).getItem());
                                ZyEquipmentTypeEntity Typef = itemf.get(0).getType();
                                if (Typef != null) {
                                    cbsEquipmentApplyDetailEntity.setTypeId(Typef);
                                    cbsEquipmentApplyDetailEntity.setTypeDes(Typef.getTypeDesc());
                                }
                            }
                        }


                        cbsEquipmentApplyDetailEntity.setSn(sn);
                        cbsEquipmentApplyDetailEntity.setTotal(Integer.valueOf(nums[i]));


                        int applyer = 0;
                        if (applers[i].equals("低")) {
                            applyer = 1;
                        } else if (applers[i].equals("中")) {
                            applyer = 2;
                        } else if (applers[i].equals("高")) {
                            applyer = 3;
                        } else if (applers[i].equals("加急")) {
                            applyer = 4;
                        }
                        cbsEquipmentApplyDetailEntity.setApplyLayer(applyer);
                        cbsEquipmentApplyDetailEntity.setMemo(applerStatement);
                        systemService.saveOrUpdate(cbsEquipmentApplyDetailEntity);
                    }
                }


                //添加故障备件序列号验证
                if (StringUtil.isNotEmpty(equipmentSns) && StringUtil.isNotEmpty(equipmentSns[0])) {
                    cbsServiceService.snValiDate(id, equipmentSns);
                }
                if (StringUtil.isNotEmpty(bjlxXlhs) && StringUtil.isNotEmpty(bjlxTexts) && !bjlxTexts.equals("-- 请选择 --") && StringUtil.isNotEmpty(equipmentSns) && StringUtil.isNotEmpty(equipmentSns[0]) && StringUtil.isNotEmpty(equipmentCodes) && StringUtil.isNotEmpty(equipmentCodes[0])) {
                    cbsServiceService.addFaultEquipment(bjlxXlhs, bjlxTexts, null, null, equipmentSns, equipmentCodes, user);
                }

                String sql = "select record_id  from cbs_equipment_apply where id='" + cbsEquipmentApply.getId() + "' ORDER BY create_date desc LIMIT 0,1";
                List<String> listbySql2 = systemService.findListbySql(sql);
                /*备件申请审批邮件提醒*/
                sendToCSA(cbsServiceEntity, listbySql2, user);

            }

            ajaxJson.setSuccess(true);
            ajaxJson.setMsg("创建成功");
        } catch (Exception e) {
            ajaxJson.setMsg("出现异常，手动回滚");
            ajaxJson.setSuccess(false);
            e.printStackTrace();
            System.err.println("事务出现异常,回滚事务！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//此处采用手动回滚
        }
        return ajaxJson;
    }

    /*获取Sr号*/
    public void getSr(final String id) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                try {
                    CbsServiceEntity cbsService = systemService.getEntity(CbsServiceEntity.class, id);
                    List<String> sr = SimpleMailReceiver.getSr();
                    String s = "";
                    for (int i = 0; i < sr.size(); i++) {
                        String[] split = sr.get(i).split("-");
                        if (sr.get(i).contains("Barco Service Request") && sr.get(i).contains(cbsService.getCode())) {
                            s = sr.get(i).substring(22, 30);
                            break;
                        }
                    }
                    System.out.println("邮件解析出来的sr=" + s);
                    logger.debug("邮件解析出来的sr=" + s);
                    cbsService.setSr(s);
                    systemService.saveOrUpdate(cbsService);
                    systemService.updateBySqlString("update cbs_equipment_apply set sr_code='" + s + "' where service_id='" + cbsService.getId() + "'");
                    systemService.updateBySqlString("update cbs_deliver set sr_code='" + s + "' where cr_code='" + cbsService.getCode() + "'");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 60000);
    }

    /**
     * app根据Id获取发货单信息
     */
    @ResponseBody
    @RequestMapping(params = "getDeliverByID")
    public AjaxJson getDeliverByID(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = request.getParameter("id");
        Map map = new HashMap();
        try {
            if (StringUtil.isNotEmpty(id)) {
                CbsDelinerEntity cbsDelinerEntity = systemService.getEntity(CbsDelinerEntity.class, id);
                if (cbsDelinerEntity != null) {
                    String messName = "";
                    String cKu = "";
                    if (StringUtil.isNotEmpty(cbsDelinerEntity.getSheng())) {
                        messName += cbsDelinerEntity.getSheng().getTerritoryName() + " ";
                    }
                    if (StringUtil.isNotEmpty(cbsDelinerEntity.getShi())) {
                        messName += cbsDelinerEntity.getShi().getTerritoryName();
                    }
                    map.put("messName", messName);
                    String thAdd = "";
                    if (StringUtil.isNotEmpty(cbsDelinerEntity.getThSheng())) {
                        thAdd += cbsDelinerEntity.getThSheng().getTerritoryName() + " ";
                    }
                    if (StringUtil.isNotEmpty(cbsDelinerEntity.getThCity())) {
                        thAdd += cbsDelinerEntity.getThCity().getTerritoryName();
                    }
                    map.put("thAdd", thAdd);
                    if (StringUtil.isNotEmpty(cbsDelinerEntity.getDeliverWarehouseId())) {
                        cKu += cbsDelinerEntity.getDeliverWarehouseId().getId();
                    }
                    map.put("cKu", cKu);
                    String hql = "from CbsServiceEntity where code='" + cbsDelinerEntity.getCrCode() + "'";
                    CbsServiceEntity cbsServiceEntity = systemService.singleResult(hql);
                    if (StringUtil.isNotEmpty(cbsServiceEntity)) {
                        map.put("cbsServiceEntity", cbsServiceEntity);
                        String hql1 = "select * FROM cbs_service_assign_list WHERE service_id='" + cbsServiceEntity.getId() + "' AND assign_torole in(2,3) AND status NOT in(2,4) ORDER BY create_date DESC LIMIT 1";
                        Map<String, Object> assignMap = systemService.findOneForJdbc(hql1);
                        if (assignMap != null) {
                            String engineerId = (String) assignMap.get("assign_touser");
                            ZyEngineerEntity zyEngineerEntity = systemService.get(ZyEngineerEntity.class, engineerId);
                            map.put("bjsqr", zyEngineerEntity.getName());
                            map.put("dh", zyEngineerEntity.getCellphone());
                            if (StringUtil.isNotEmpty(zyEngineerEntity.getBelongOrg())) {
                                map.put("orgName", StringUtil.isNotEmpty(zyEngineerEntity.getBelongOrg().getDepartname()) ? zyEngineerEntity.getBelongOrg().getDepartname() : "");
                            } else {
                                map.put("orgName", "");
                            }
                        }
                    }

                    List<Map<String, Object>> cbsDeliverEquipmentList = systemService.findForJdbc("SELECT\n" +
                            "\tIFNULL(d.id, '') AS id,\n" +
                            "\tIFNULL(d.type_id, '') AS typeId,\n" +
                            "\tIFNULL(d.item_id, '') AS itemId,\n" +
                            "\tIFNULL(d.item, '') AS item,\n" +
                            "\tIFNULL(t.type_desc, '') AS typeDesc,\n" +
                            "\tIFNULL(d.is_return, '') AS isReturn,\n" +
                            "\tCASE\n" +
                            "WHEN apply_layer = '1' THEN\n" +
                            "\t'低'\n" +
                            "WHEN apply_layer = '2' THEN\n" +
                            "\t'中'\n" +
                            "WHEN apply_layer = '3' THEN\n" +
                            "\t'高'\n" +
                            "ELSE\n" +
                            "\t''\n" +
                            "END AS applyLayer\n" +
                            "FROM\n" +
                            "\tcbs_deliver_equipment d\n" +
                            "LEFT JOIN zy_equipment_type t ON t.id = d.type_id\n" +
                            "LEFT JOIN zy_es_item it ON it.id = d.item_id\n" +
                            "WHERE\n" +
                            "\tdeliver_id = '" + id + "'");
                    if (cbsDeliverEquipmentList != null) {
                        map.put("cbsDeliverEquipmentList", cbsDeliverEquipmentList);
                    }
                    //查询物流
                    String hq2 = "from TSDepart where orgType='logistics'";
                    List<TSDepart> tsDepartList = systemService.findHql(hq2);
                    map.put("tsDepartList", tsDepartList);
                    List<CbsWarehouseEntity> cbsWarehouseEntities = systemService.findHql("from CbsWarehouseEntity where isClose = '0'");
                    map.put("cbsWarehouseEntities", cbsWarehouseEntities);
                    map.put("cbsDeliverEntity", cbsDelinerEntity);
                    if (StringUtil.isNotEmpty(cbsDelinerEntity.getEquipmentApplyId())) {
                        map.put("csaDesc", StringUtil.isNotEmpty(cbsDelinerEntity.getEquipmentApplyId().getCsaAttention()) ? cbsDelinerEntity.getEquipmentApplyId().getCsaAttention() : "");
                    } else {
                        map.put("csaDesc", "");
                    }
                    //查询库位
                    String kw = "from TSType where TSTypegroup.typegroupcode='kuwei'";
                    List<TSType> tSTypeList = systemService.findHql(kw);
                    map.put("tSTypeList", tSTypeList);
                    //查询库位
                    String slaType = "from TSType where TSTypegroup.typegroupcode='fhSLA'";
                    List<TSType> slaTypeList = systemService.findHql(slaType);
                    map.put("slaTypeList", slaTypeList);
                }
                ajaxJson.setAttributes(map);
                ajaxJson.setSuccess(true);
            }
        } catch (Exception e) {
            e.getMessage();
            ajaxJson.setSuccess(false);
        }
        return ajaxJson;
    }

    /**
     * 物流发货详情跳转
     */
    @ResponseBody
    @RequestMapping(params = "getDeliverDetailsById")
    public AjaxJson getDeliverDetailsById(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        try {
            String id = request.getParameter("id");
            List<Map<String, Object>> cbsDeliverEquipmentList = systemService.findForJdbc("SELECT\n" +
                    "\tIFNULL(ed.id, '') AS eqId,IFNULL(d.`code`, '') AS `code`,\n" +
                    "\tIFNULL(ed.type_des, '') AS typeDesc,\n" +
                    "\tIFNULL(ed.item, '') AS item,\n" +
                    "\tIFNULL(d.deliver_warehouse_id, '') AS warehouse,\n" +
                    "\tIFNULL(d.warehouse_position, '') AS warehousePosition\n" +
                    "FROM\n" +
                    "\tcbs_deliver_equipment ed \n" +
                    "LEFT JOIN cbs_deliver d ON d.id = ed.deliver_id\n" +
                    "WHERE\n" +
                    "\ted.deliver_id = '" + id + "'");
            map.put("cbsDeliverEquipmentList", cbsDeliverEquipmentList);
            CbsDelinerEntity cbsDelinerEntity = systemService.getEntity(CbsDelinerEntity.class, id);
            map.put("cbsDeliverEntity", cbsDelinerEntity);
            if (cbsDelinerEntity.getDeliverWarehouseId() != null) {
                map.put("warouseId", cbsDelinerEntity.getDeliverWarehouseId().getId());
            }
            String messName = "";
            if (StringUtil.isNotEmpty(cbsDelinerEntity.getSheng())) {
                messName += cbsDelinerEntity.getSheng().getTerritoryName() + " ";
            }
            if (StringUtil.isNotEmpty(cbsDelinerEntity.getShi())) {
                messName += cbsDelinerEntity.getShi().getTerritoryName();
            }
            map.put("messName", messName);
            //获取发货sla
            TSType fhSLA = systemService.singleResult("from TSType where typecode='" + cbsDelinerEntity.getFhSLA() + "' and TSTypegroup.typegroupcode='fhSLA'");
            map.put("fhSLA", fhSLA);
            List<TSType> kws = systemService.findHql("from TSType where  TSTypegroup.typegroupcode='kuwei'");
            map.put("kws", kws);
            List<CbsWarehouseEntity> cbsWarehouseEntityList = systemService.findHql("from CbsWarehouseEntity where isClose = '0' and logistics = '" + cbsDelinerEntity.getDeliverLogistics() + "'");
            map.put("cbsWarehouseEntityList", cbsWarehouseEntityList);
            String hql = "from CbsServiceEntity where code='" + cbsDelinerEntity.getCrCode() + "'";
            CbsServiceEntity cbsServiceEntity = systemService.singleResult(hql);
            if (cbsServiceEntity != null) {


                String hql1 = "select * FROM cbs_service_assign_list WHERE service_id='" + cbsServiceEntity.getId() + "' AND assign_torole in(2,3) AND status NOT in(2,4) ORDER BY create_date DESC LIMIT 1";
                Map<String, Object> assignMap = systemService.findOneForJdbc(hql1);
                if (assignMap != null) {
                    String engineerId = (String) assignMap.get("assign_touser");
                    ZyEngineerEntity engineer = systemService.get(ZyEngineerEntity.class, engineerId);
                    map.put("engineerName", engineer.getName());
                    map.put("cellPhone", engineer.getCellphone());
                    if (StringUtil.isNotEmpty(engineer)) {
                        map.put("group", engineer.getBelongOrg().getDepartname());
                    }
                }
            }
            //获取服务工程师信息
            ajaxJson.setSuccess(true);
            ajaxJson.setAttributes(map);
        } catch (Exception e) {
            e.getMessage();
            ajaxJson.setSuccess(false);
        }
        return ajaxJson;
    }

    /**
     * 物流角色获取发货单信息
     */
    @RequestMapping(params = "getDataForLogistics")
    @ResponseBody
    public AjaxJson getDataForLogistics(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        String code = request.getParameter("code");
        Map map = new HashMap();
        try {
            TSUser user = ResourceUtil.getSessionUserName();
            String logisticsName = user.getCurrentDepart().getDepartname();
            System.out.println("logisticsName:" + logisticsName);
            String sql = "SELECT\n" +
                    "\tIFNULL(d.id, '') AS id,\n" +
                    "\tIFNULL(d.`code`, '') AS `code`,\n" +
                    "\tIFNULL(d.cinema_name, '') AS cinemaName,\n" +
                    "\tIFNULL(d.deliver_des, '') AS deliverDes,\n" +
                    "\tIFNULL(d.address, '') AS address,\n" +
                    "\tIFNULL(CASE d.`status`\n" +
                    "WHEN '1' THEN\n" +
                    "\t'CSA待发货'\n" +
                    "WHEN '2' THEN\n" +
                    "\t'CSA已发货'\n" +
                    "WHEN '4' THEN\n" +
                    "\t'欠货中'\n" +
                    "WHEN '5' THEN\n" +
                    "\t'物流待发货'\n" +
                    "WHEN '6' THEN\n" +
                    "\t'物流已发货'\n" +
                    "WHEN '7' THEN\n" +
                    "\t'已签收'\n" +
                    "WHEN '9' THEN\n" +
                    "\t'CSA取消发货'\n" +
                    "END,'') as `status`,\n" +
                    "\tIFNULL(d.deliver_logistics, '') AS deliverLogistics,\n" +
                    "\tIFNULL(d.create_date, '') AS createDate\n" +
                    "FROM\n" +
                    "\tcbs_deliver d\n" +
                    "WHERE 1 = 1 AND d.deliver_logistics = '" + logisticsName + "'\n" +
                    "AND d. STATUS IN ('5')";
            if (StringUtil.isNotEmpty(code)) {
                sql += " and d.`code` like '%" + code + "%'";
            }
            sql += "ORDER BY\n" +
                    "\td.`status` ASC,\n" +
                    "\td.create_date DESC,\n" +
                    "\td.cinema_name ASC";
            List<Map<String, Object>> cbsDeliverList = systemService.findForJdbc(sql);

            System.out.println(cbsDeliverList);
            map.put("cbsDeliverList", cbsDeliverList);
            ajaxJson.setSuccess(true);
            ajaxJson.setAttributes(map);
        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.getMessage();
        }
        return ajaxJson;

    }

    /**
     * app判断是否已经发货
     */
    @ResponseBody
    @RequestMapping(params = "ifSend")
    public AjaxJson ifSend(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        try {
            String id = request.getParameter("id");
            CbsDelinerEntity cbsDelinerEntity = systemService.getEntity(CbsDelinerEntity.class, id);
            if (Integer.valueOf(cbsDelinerEntity.getStatus()) > 5) {
                ajaxJson.setSuccess(true);
            } else {
                ajaxJson.setSuccess(false);
            }
        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.getMessage();
        }
        return ajaxJson;
    }

    /**
     * app Csa判断是否已经发货
     */
    @ResponseBody
    @RequestMapping(params = "ifSendByCsa")
    public AjaxJson ifSendByCsa(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        try {
            String id = request.getParameter("id");
            CbsDelinerEntity cbsDelinerEntity = systemService.getEntity(CbsDelinerEntity.class, id);
            if (StringUtil.isNotEmpty(cbsDelinerEntity)) {
                ajaxJson.setSuccess(true);
                map.put("cbsDelinerEntity", cbsDelinerEntity);
            } else {
                ajaxJson.setSuccess(false);
            }
            ajaxJson.setAttributes(map);
        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.getMessage();
        }
        return ajaxJson;
    }

    /**
     * CSA角色获取发货单信息
     */
    @RequestMapping(params = "getDataForLCSA")
    @ResponseBody
    public AjaxJson getDataForLCSA(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        try {
            String code = request.getParameter("code");
            String num = request.getParameter("page");
//            System.out.println("num=" + num);
            StringBuffer sql = new StringBuffer("SELECT IFNULL(d.id, '') AS id, IFNULL(d.`code`, '') AS `code`,");
            sql.append("IFNULL(d.cinema_name, '') AS cinemaName,IFNULL(d.deliver_des, '') AS deliverDes,");
            sql.append("IFNULL(d.address, '') AS address,IFNULL(d.deliver_logistics, '') AS deliverLogistics,");
            sql.append("IFNULL(d.create_date, '') AS createDate,IFNULL(d.expecttime, '') AS expecttime,");
            sql.append("IFNULL( CASE d.`status` WHEN '1' THEN 'CSA待发货' WHEN '2' THEN 'CSA已发货' WHEN '4' THEN '欠货中' WHEN '5' THEN '物流待发货' WHEN '6' THEN '物流已发货' END, '' ) AS `status` ");
            sql.append(" FROM cbs_deliver d WHERE d.`status` !='9' AND d.`status` != '7' ");
            if (StringUtil.isNotEmpty(code)) {
                sql.append(" and d.`code` like '%" + code + "%'");
            } else {
                sql.append("ORDER BY d.`status` ASC,d.create_date DESC,d.cinema_name ASC");
            }
            sql.append(" limit ").append(Integer.parseInt(num) * 6).append(",6 ");

//            System.out.println("sql=" + sql);
            List<Map<String, Object>> cbsDeliverList = systemService.findForJdbc(sql.toString());

            map.put("cbsDeliverList", cbsDeliverList);
            ajaxJson.setSuccess(true);
            ajaxJson.setAttributes(map);
        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.getMessage();
        }
        return ajaxJson;

    }

    /**
     * csa发货
     *
     * @param request
     * @return
     */
    @RequestMapping(params = "sendByCsa")
    @ResponseBody
    public AjaxJson sendByCsa(HttpServletRequest request) {
        AjaxJson ajaxJson = new AjaxJson();
        Map map = new HashMap();
        TSUser user = ResourceUtil.getSessionUserName();
        try {
            String id1 = request.getParameter("id");
            String logistics = request.getParameter("logistics");
            String warouse = request.getParameter("warouse");
            String kw = request.getParameter("kw");
            String thAddress = request.getParameter("thAddress");
            String sendDes = request.getParameter("sendDes");
            String returnLogistics = request.getParameter("returnLogistics");
            String status = request.getParameter("status");
            String fhSla = request.getParameter("fhSla");
            String[] equipmentId = request.getParameterValues("equipmentIds");
            String address = request.getParameter("address");
            if (" --请选择--".equals(address)) {
                address = null;
            }
            TSTerritory tsTerritory = null;
            TSTerritory tsTerritory1 = null;
            if (StringUtil.isNotEmpty(address)) {
                String[] split = address.split(" ");
                if ("重庆".equals(split[0])) {
                    split[0] = "重庆市";
                }
                if ("宁夏".equals(split[0])) {
                    split[0] = "宁夏省";
                }
                if ("西藏".equals(split[0])) {
                    split[0] = "西藏自治区";
                }
                if ("新疆".equals(split[0])) {
                    split[0] = "新疆维吾尔自治区";
                }
                if ("广西壮族".equals(split[0])) {
                    split[0] = "广西省";
                }
                if ("内蒙古".equals(split[0])) {
                    split[0] = "内蒙古自治区";
                }
                //发货省
                tsTerritory = systemService.singleResult("from TSTerritory where territoryName = '" + split[0] + "' and territoryLevel = 1");
                //发货市

                if (split[0].equals("北京市") || split[0].equals("天津市") || split[0].equals("上海市") || split[0].equals("重庆")) {
                    if ("重庆".equals(split[1])) {
                        split[0] = "重庆市";
                    }
                    tsTerritory1 = systemService.singleResult("from TSTerritory where territoryName = '" + split[0] + "' and territoryLevel = 2");
                } else {
                    tsTerritory1 = systemService.singleResult("from TSTerritory where territoryName = '" + split[1] + "' and territoryLevel = 2");
                }
            }

            String equipmentIds = "";

            if (equipmentId != null && equipmentId.length > 0) {
                for (int j = 0; j < equipmentId.length; j++) {
                    equipmentIds += equipmentId[j] + ",";
                }
            }
            CbsDelinerEntity cbsDelinerEntity = systemService.getEntity(CbsDelinerEntity.class, id1);
            cbsDelinerEntity.setDeliverLogistics(logistics);
            CbsWarehouseEntity cbsWarehouseEntity = new CbsWarehouseEntity();
            cbsWarehouseEntity.setId(warouse);
            cbsDelinerEntity.setDeliverWarehouseId(cbsWarehouseEntity);
            cbsDelinerEntity.setwLocaltion(kw);
            cbsDelinerEntity.setFhSLA(fhSla);
            cbsDelinerEntity.setThSheng(tsTerritory);
            cbsDelinerEntity.setThCity(tsTerritory1);
            cbsDelinerEntity.setThAddress(thAddress);
            cbsDelinerEntity.setDeliverDes(sendDes);
            cbsDelinerEntity.setReturnLogistics(returnLogistics);
            systemService.saveOrUpdate(cbsDelinerEntity);
            Date date = new Date();
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = format.format(date);
            if (StaticValue.wldfh.equals(status) || StaticValue.wlyfh.equals(status)) {
                int i = systemService.updateBySqlString("UPDATE cbs_deliver set status =" + StaticValue.wldfh + ",csa_sendtime='" + time + "',deliver_logistics = '" + logistics + "',deliver_warehouse_id = '" + warouse + "',WAREHOUSE_POSITION='" + kw + "',DELIVER_DES='" + sendDes + "',return_logistics='" + returnLogistics + "',FH_SLA = '" + fhSla + "' where id='" + id1 + "'");
            }
            if (StringUtil.isNotEmpty(tsTerritory) && StringUtil.isNotEmpty(tsTerritory1)) {
                systemService.updateBySqlString("update cbs_deliver set th_sheng = '" + tsTerritory.getId() + "',th_city='" + tsTerritory1.getId() + "',th_address='" + thAddress + "' where id = '" + id1 + "'");
            }
            if (StaticValue.CSAdfh.equals(status)) {
                systemService.updateBySqlString("UPDATE cbs_deliver set status =" + StaticValue.wldfh + ",csa_sendtime='" + time + "',deliver_logistics = '" + logistics + "',deliver_warehouse_id = '" + warouse + "',WAREHOUSE_POSITION='" + kw + "',th_address='" + thAddress + "',DELIVER_DES='" + sendDes + "',return_logistics='" + returnLogistics + "',FH_SLA = '" + fhSla + "' where id='" + id1 + "'");
                String string = "";
                String string1 = "";
                if (StringUtil.isNotEmpty(equipmentIds)) {
                    equipmentIds = equipmentIds.substring(0, equipmentIds.length() - 1);
                    if (equipmentIds.contains(",")) {
                        int j = 0;
                        for (String id : equipmentIds.split(",")) {
                            CbsDeliverEquipmentEntity cbsDeliverEquipmentEntity = systemService.getEntity(CbsDeliverEquipmentEntity.class, id.trim());
                            if (cbsDeliverEquipmentEntity != null) {

                                if (cbsDeliverEquipmentEntity.getIsReturn() != null && cbsDeliverEquipmentEntity.getIsReturn() == 2) {
                                    CbsReturnEquipmentEntity cbsReturnEquipmentEntity = getcbsReturnEquipmentEntiy();
                                    CbsReturnEquipmentDetailEntity cbsReturnEquipmentDetailEntity1 = getCbsReturnEquipmentDetailEntity();
                                    //TODO 创建返件任务
                                    Date date1 = new Date();
                                    DateFormat format1 = new SimpleDateFormat("yyyyMMdd");
                                    String time1 = format1.format(date1);
                                    StringBuffer buffer = new StringBuffer();
                                    buffer.append("FJ");
                                    buffer.append(time1);
                                    List<Object[]> objects = systemService.findListbySql("select * from cbs_return_equipment where to_days(create_date) = to_days(now()) ORDER BY `code` desc;");
                                    if (objects.size() == 0) {
                                        buffer.append("001");
                                        string1 = buffer.toString();
                                        CbsReturnEquipmentEntity returnEquipmentEntity = null;
                                        if (j == 0) {
                                            //判断返件表中是否存在该数据
                                            returnEquipmentEntity = systemService.singleResult("from CbsReturnEquipmentEntity where deliverCode = '" + cbsDelinerEntity.getCode() + "'");
                                            if (returnEquipmentEntity == null) {
                                                cbsReturnEquipmentEntity.setCode(string1);
                                                cbsReturnEquipmentEntity.setSrCode(cbsDelinerEntity.getSrCode());
                                                cbsReturnEquipmentEntity.setCinemaName(cbsDelinerEntity.getCinemaName());
                                                cbsReturnEquipmentEntity.setName(cbsDelinerEntity.getUserName());
                                                cbsReturnEquipmentEntity.setPhone(cbsDelinerEntity.getPhone());
                                                cbsReturnEquipmentEntity.setAddress(cbsDelinerEntity.getAddress());
                                                cbsReturnEquipmentEntity.setSoCode(cbsDelinerEntity.getSoCode());
                                                cbsReturnEquipmentEntity.setDeliverCode(cbsDelinerEntity.getCode());
                                                cbsReturnEquipmentEntity.setCrCode(cbsDelinerEntity.getCrCode());
                                                cbsReturnEquipmentEntity.setSheng(cbsDelinerEntity.getSheng());
                                                cbsReturnEquipmentEntity.setShi(cbsDelinerEntity.getShi());
                                                cbsReturnEquipmentEntity.setEquipmentApplyId(cbsDelinerEntity.getEquipmentApplyId());
                                                cbsReturnEquipmentEntity.setStatus(StaticValue.RETURN_STATUS_Log_Type_1);
                                                cbsReturnEquipmentEntity.setLogistics(cbsDelinerEntity.getReturnLogistics());
                                                cbsReturnEquipmentEntity.setLogisticsCode(cbsDeliverEquipmentEntity.getLogisticsNumber());
                                                cbsReturnEquipmentServiceI.save(cbsReturnEquipmentEntity);
                                                j++;
                                            }
                                        }
                                        if (returnEquipmentEntity == null) {
                                            List<Map<String, Object>> forJdbc = systemService.findForJdbc("SELECT\n" +
                                                    "*\n" +
                                                    "FROM\n" +
                                                    "\tcbs_return_equipment_detail\n" +
                                                    "WHERE\n" +
                                                    "\tdeliver_equuipment_id = '" + equipmentIds.trim() + "'\n" +
                                                    "AND return_equipment_id = '" + cbsReturnEquipmentEntity.getId() + "'");
                                            if (forJdbc == null || forJdbc.size() == 0) {
                                                List<CbsReturnEquipmentEntity> cbsReturnEquipmentEntity1 = systemService.findHql("from CbsReturnEquipmentEntity where deliverCode = '" + cbsDelinerEntity.getCode() + "'");
                                                if (cbsReturnEquipmentEntity1.size() > 0) {
                                                    cbsReturnEquipmentDetailEntity1.setReturnEquipmentId(cbsReturnEquipmentEntity1.get(0));
                                                }
                                                cbsReturnEquipmentDetailEntity1.setTypeId(cbsDeliverEquipmentEntity.getTypeId());
                                                cbsReturnEquipmentDetailEntity1.setTypeDes(cbsDeliverEquipmentEntity.getTypeDes());
                                                cbsReturnEquipmentDetailEntity1.setItemId(cbsDeliverEquipmentEntity.getItemId());
                                                cbsReturnEquipmentDetailEntity1.setItem(cbsDeliverEquipmentEntity.getItem());
                                                cbsReturnEquipmentDetailEntity1.setItemTotal(cbsDeliverEquipmentEntity.getTotal());
                                                cbsReturnEquipmentDetailEntity1.setSn(cbsDeliverEquipmentEntity.getSn());
                                                cbsReturnEquipmentDetailEntity1.setDeliverEquipmentId(cbsDeliverEquipmentEntity);
                                                cbsReturnEquipmentDetailServiceI.save(cbsReturnEquipmentDetailEntity1);
                                            }
                                        }


                                    } else {
                                        String o = (String) objects.get(0)[1];
                                        String s = o.substring(10, 13);
                                        int i = Integer.parseInt(s);
                                        i++;
                                        if (i <= 9) {
                                            buffer.append("00" + i);
                                        } else if (i >= 10 && i < 100) {
                                            buffer.append("0" + i);
                                        } else {
                                            buffer.append(i);
                                        }
                                        string = buffer.toString();
                                        CbsReturnEquipmentEntity returnEquipmentEntity = null;
                                        if (j == 0) {
                                            //判断返件表中是否存在该数据
                                            returnEquipmentEntity = systemService.singleResult("from CbsReturnEquipmentEntity where deliverCode = '" + cbsDelinerEntity.getCode() + "'");
                                            if (returnEquipmentEntity == null) {
                                                cbsReturnEquipmentEntity.setCode(string);
                                                cbsReturnEquipmentEntity.setSrCode(cbsDelinerEntity.getSrCode());
                                                cbsReturnEquipmentEntity.setSoCode(cbsDelinerEntity.getSoCode());
                                                cbsReturnEquipmentEntity.setDeliverCode(cbsDelinerEntity.getCode());
                                                cbsReturnEquipmentEntity.setCrCode(cbsDelinerEntity.getCrCode());
                                                cbsReturnEquipmentEntity.setCinemaName(cbsDelinerEntity.getCinemaName());
                                                cbsReturnEquipmentEntity.setName(cbsDelinerEntity.getUserName());
                                                cbsReturnEquipmentEntity.setPhone(cbsDelinerEntity.getPhone());
                                                cbsReturnEquipmentEntity.setAddress(cbsDelinerEntity.getAddress());
                                                cbsReturnEquipmentEntity.setSheng(cbsDelinerEntity.getSheng());
                                                cbsReturnEquipmentEntity.setShi(cbsDelinerEntity.getShi());
                                                cbsReturnEquipmentEntity.setEquipmentApplyId(cbsDelinerEntity.getEquipmentApplyId());
                                                cbsReturnEquipmentEntity.setLogistics(cbsDelinerEntity.getReturnLogistics());
                                                cbsReturnEquipmentEntity.setLogisticsCode(cbsDeliverEquipmentEntity.getLogisticsNumber());
                                                cbsReturnEquipmentEntity.setStatus(StaticValue.RETURN_STATUS_Log_Type_1);
                                                cbsReturnEquipmentServiceI.save(cbsReturnEquipmentEntity);
                                                j++;
                                            }

                                        }
                                        if (returnEquipmentEntity == null) {
                                            List<Map<String, Object>> forJdbc = systemService.findForJdbc("SELECT\n" +
                                                    "*\n" +
                                                    "FROM\n" +
                                                    "\tcbs_return_equipment_detail\n" +
                                                    "WHERE\n" +
                                                    "\tdeliver_equuipment_id = '" + equipmentIds.trim() + "'\n" +
                                                    "AND return_equipment_id = '" + cbsReturnEquipmentEntity.getId() + "'");
                                            if (forJdbc == null || forJdbc.size() == 0) {
                                                List<CbsReturnEquipmentEntity> cbsReturnEquipmentEntity1 = systemService.findHql("from CbsReturnEquipmentEntity where deliverCode = '" + cbsDelinerEntity.getCode() + "'");
                                                if (cbsReturnEquipmentEntity1.size() > 0) {
                                                    cbsReturnEquipmentDetailEntity1.setReturnEquipmentId(cbsReturnEquipmentEntity1.get(0));
                                                }
                                                cbsReturnEquipmentDetailEntity1.setTypeId(cbsDeliverEquipmentEntity.getTypeId());
                                                cbsReturnEquipmentDetailEntity1.setTypeDes(cbsDeliverEquipmentEntity.getTypeDes());
                                                cbsReturnEquipmentDetailEntity1.setItemId(cbsDeliverEquipmentEntity.getItemId());
                                                cbsReturnEquipmentDetailEntity1.setItem(cbsDeliverEquipmentEntity.getItem());
                                                cbsReturnEquipmentDetailEntity1.setItemTotal(cbsDeliverEquipmentEntity.getTotal());
                                                cbsReturnEquipmentDetailEntity1.setSn(cbsDeliverEquipmentEntity.getSn());
                                                cbsReturnEquipmentDetailEntity1.setDeliverEquipmentId(cbsDeliverEquipmentEntity);
                                                cbsReturnEquipmentDetailServiceI.save(cbsReturnEquipmentDetailEntity1);
                                            }
                                        }
                                    }
                                    //创建返件日志
                                    CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                                    cbsHandleLogEntity.setBusinessId(cbsReturnEquipmentEntity.getId());
                                    cbsHandleLogEntity.setLogType(4);
                                    cbsHandleLogEntity.setDescription("创建返件申请单");
                                    cbsHandleLogEntity.setCreateName(user.getRealName());
                                    cbsHandleLogEntity.setCreateBy(user.getUserName());
                                    systemService.saveOrUpdate(cbsHandleLogEntity);
                                }
                            }
                        }
                    } else {
                        System.out.println("ID:" + equipmentIds);
                        int j = 0;
                        CbsDeliverEquipmentEntity cbsDeliverEquipmentEntity = systemService.getEntity(CbsDeliverEquipmentEntity.class, equipmentIds.trim());
                        if (cbsDeliverEquipmentEntity != null) {
                            if (cbsDeliverEquipmentEntity.getIsReturn() != null && cbsDeliverEquipmentEntity.getIsReturn() == 2) {
                                CbsReturnEquipmentEntity cbsReturnEquipmentEntity = getcbsReturnEquipmentEntiy();
                                CbsReturnEquipmentDetailEntity cbsReturnEquipmentDetailEntity1 = getCbsReturnEquipmentDetailEntity();
                                //TODO 创建返件任务
                                Date date1 = new Date();
                                DateFormat format1 = new SimpleDateFormat("yyyyMMdd");
                                String time1 = format1.format(date1);
                                StringBuffer buffer = new StringBuffer();
                                buffer.append("FJ");
                                buffer.append(time1);
                                List<Object[]> objects = systemService.findListbySql("select * from cbs_return_equipment where to_days(create_date) = to_days(now()) ORDER BY `code` desc;");
                                if (objects.size() == 0) {
                                    buffer.append("001");
                                    string1 = buffer.toString();
                                    CbsReturnEquipmentEntity returnEquipmentEntity = null;
                                    if (j == 0) {
                                        //判断返件表中是否存在该数据
                                        returnEquipmentEntity = systemService.singleResult("from CbsReturnEquipmentEntity where deliverCode = '" + cbsDelinerEntity.getCode() + "'");
                                        if (returnEquipmentEntity == null) {
                                            cbsReturnEquipmentEntity.setCode(string1);
                                            cbsReturnEquipmentEntity.setSrCode(cbsDelinerEntity.getSrCode());
                                            cbsReturnEquipmentEntity.setSoCode(cbsDelinerEntity.getSoCode());
                                            cbsReturnEquipmentEntity.setCrCode(cbsDelinerEntity.getCrCode());
                                            cbsReturnEquipmentEntity.setDeliverCode(cbsDelinerEntity.getCode());
                                            cbsReturnEquipmentEntity.setCinemaName(cbsDelinerEntity.getCinemaName());
                                            cbsReturnEquipmentEntity.setName(cbsDelinerEntity.getUserName());
                                            cbsReturnEquipmentEntity.setPhone(cbsDelinerEntity.getPhone());
                                            cbsReturnEquipmentEntity.setAddress(cbsDelinerEntity.getAddress());
                                            cbsReturnEquipmentEntity.setSheng(cbsDelinerEntity.getSheng());
                                            cbsReturnEquipmentEntity.setShi(cbsDelinerEntity.getShi());
                                            cbsReturnEquipmentEntity.setEquipmentApplyId(cbsDelinerEntity.getEquipmentApplyId());
                                            cbsReturnEquipmentEntity.setStatus(StaticValue.RETURN_STATUS_Log_Type_1);
                                            cbsReturnEquipmentServiceI.save(cbsReturnEquipmentEntity);
                                            j++;
                                        }
                                    }
                                    //如果returnEquipmentEntity为NULL就证明 已经执行过返件主表的操作
                                    if (returnEquipmentEntity == null) {
                                        List<Map<String, Object>> forJdbc = systemService.findForJdbc("SELECT\n" +
                                                "*\n" +
                                                "FROM\n" +
                                                "\tcbs_return_equipment_detail\n" +
                                                "WHERE\n" +
                                                "\tdeliver_equuipment_id = '" + equipmentIds.trim() + "'\n" +
                                                "AND return_equipment_id = '" + cbsReturnEquipmentEntity.getId() + "'");
                                        if (forJdbc == null || forJdbc.size() == 0) {
                                            List<CbsReturnEquipmentEntity> cbsReturnEquipmentEntity1 = systemService.findHql("from CbsReturnEquipmentEntity where deliverCode = '" + cbsDelinerEntity.getCode() + "'");
                                            if (cbsReturnEquipmentEntity1.size() > 0) {
                                                cbsReturnEquipmentDetailEntity1.setReturnEquipmentId(cbsReturnEquipmentEntity1.get(0));
                                            }
                                            cbsReturnEquipmentDetailEntity1.setTypeId(cbsDeliverEquipmentEntity.getTypeId());
                                            cbsReturnEquipmentDetailEntity1.setTypeDes(cbsDeliverEquipmentEntity.getTypeDes());
                                            cbsReturnEquipmentDetailEntity1.setItemId(cbsDeliverEquipmentEntity.getItemId());
                                            cbsReturnEquipmentDetailEntity1.setItem(cbsDeliverEquipmentEntity.getItem());
                                            cbsReturnEquipmentDetailEntity1.setItemTotal(cbsDeliverEquipmentEntity.getTotal());
                                            cbsReturnEquipmentDetailEntity1.setSn(cbsDeliverEquipmentEntity.getSn());
                                            cbsReturnEquipmentDetailEntity1.setDeliverEquipmentId(cbsDeliverEquipmentEntity);
                                            cbsReturnEquipmentDetailServiceI.save(cbsReturnEquipmentDetailEntity1);
                                        }
                                    }

                                } else {
                                    String o = (String) objects.get(0)[1];
                                    String s = o.substring(10, 13);
                                    int i = Integer.parseInt(s);
                                    i++;
                                    if (i <= 9) {
                                        buffer.append("00" + i);
                                    } else if (i >= 10 && i < 100) {
                                        buffer.append("0" + i);
                                    } else {
                                        buffer.append(i);
                                    }
                                    string = buffer.toString();
                                    CbsReturnEquipmentEntity returnEquipmentEntity = null;
                                    if (j == 0) {
                                        //判断返件表中是否存在该数据
                                        returnEquipmentEntity = systemService.singleResult("from CbsReturnEquipmentEntity where deliverCode = '" + cbsDelinerEntity.getCode() + "'");
                                        if (returnEquipmentEntity == null) {
                                            cbsReturnEquipmentEntity.setCode(string);
                                            cbsReturnEquipmentEntity.setSrCode(cbsDelinerEntity.getSrCode());
                                            cbsReturnEquipmentEntity.setSoCode(cbsDelinerEntity.getSoCode());
                                            cbsReturnEquipmentEntity.setCrCode(cbsDelinerEntity.getCrCode());
                                            cbsReturnEquipmentEntity.setDeliverCode(cbsDelinerEntity.getCode());
                                            cbsReturnEquipmentEntity.setCinemaName(cbsDelinerEntity.getCinemaName());
                                            cbsReturnEquipmentEntity.setName(cbsDelinerEntity.getUserName());
                                            cbsReturnEquipmentEntity.setPhone(cbsDelinerEntity.getPhone());
                                            cbsReturnEquipmentEntity.setAddress(cbsDelinerEntity.getAddress());
                                            cbsReturnEquipmentEntity.setEquipmentApplyId(cbsDelinerEntity.getEquipmentApplyId());
                                            cbsReturnEquipmentEntity.setLogisticsCode(cbsDeliverEquipmentEntity.getLogisticsNumber());
                                            cbsReturnEquipmentEntity.setLogistics(cbsDelinerEntity.getReturnLogistics());
                                            cbsReturnEquipmentEntity.setSheng(cbsDelinerEntity.getSheng());
                                            cbsReturnEquipmentEntity.setShi(cbsDelinerEntity.getShi());
                                            cbsReturnEquipmentEntity.setStatus(StaticValue.RETURN_STATUS_Log_Type_1);
                                            cbsReturnEquipmentServiceI.save(cbsReturnEquipmentEntity);
                                            j++;
                                        }
                                    }
                                    if (returnEquipmentEntity == null) {
                                        List<Map<String, Object>> forJdbc = systemService.findForJdbc("SELECT\n" +
                                                "*\n" +
                                                "FROM\n" +
                                                "\tcbs_return_equipment_detail\n" +
                                                "WHERE\n" +
                                                "\tdeliver_equuipment_id = '" + equipmentIds.trim() + "'\n" +
                                                "AND return_equipment_id = '" + cbsReturnEquipmentEntity.getId() + "'");
//                                    CbsReturnEquipmentDetailEntity cbsReturnEquipmentDetailEntity = systemService.singleResult("from CbsReturnEquipmentDetailEntity where deliverEquuipmentId.id = '"+equipmentIds.trim()+"' and returnEquipmentId.id = '"+returnEquipmentEntity.getId()+"'");
                                        if (forJdbc == null || forJdbc.size() == 0) {
                                            List<CbsReturnEquipmentEntity> cbsReturnEquipmentEntity1 = systemService.findHql("from CbsReturnEquipmentEntity where deliverCode = '" + cbsDelinerEntity.getCode() + "'");
                                            if (cbsReturnEquipmentEntity1.size() > 0) {
                                                cbsReturnEquipmentDetailEntity1.setReturnEquipmentId(cbsReturnEquipmentEntity1.get(0));
                                            }
                                            cbsReturnEquipmentDetailEntity1.setTypeId(cbsDeliverEquipmentEntity.getTypeId());
                                            cbsReturnEquipmentDetailEntity1.setTypeDes(cbsDeliverEquipmentEntity.getTypeDes());
                                            cbsReturnEquipmentDetailEntity1.setItemId(cbsDeliverEquipmentEntity.getItemId());
                                            cbsReturnEquipmentDetailEntity1.setItem(cbsDeliverEquipmentEntity.getItem());
                                            cbsReturnEquipmentDetailEntity1.setItemTotal(cbsDeliverEquipmentEntity.getTotal());
                                            cbsReturnEquipmentDetailEntity1.setSn(cbsDeliverEquipmentEntity.getSn());
                                            cbsReturnEquipmentDetailEntity1.setDeliverEquipmentId(cbsDeliverEquipmentEntity);
                                            cbsReturnEquipmentDetailServiceI.save(cbsReturnEquipmentDetailEntity1);
                                        }
                                    }


                                }
                                //创建返件日志
                                CbsHandleLogEntity cbsHandleLogEntity = new CbsHandleLogEntity();
                                cbsHandleLogEntity.setBusinessId(cbsReturnEquipmentEntity.getId());
                                cbsHandleLogEntity.setLogType(4);
                                cbsHandleLogEntity.setDescription("创建返件申请单");
                                cbsHandleLogEntity.setCreateName(user.getRealName());
                                cbsHandleLogEntity.setCreateBy(user.getUserName());
                                systemService.saveOrUpdate(cbsHandleLogEntity);
                            }
                        }
                    }
                }
            }
            ajaxJson.setSuccess(true);
            cbsDelinerService.addDeliverLog(user.getRealName() + "已发货", cbsDelinerEntity.getId(), 2);
            String code = StringUtil.isNotEmpty(cbsDelinerEntity.getCode()) ? cbsDelinerEntity.getCode() : "";
            String crCode = StringUtil.isNotEmpty(cbsDelinerEntity.getCrCode()) ? cbsDelinerEntity.getCrCode() : "";
            String cinemaName = StringUtil.isNotEmpty(cbsDelinerEntity.getCinemaName()) ? cbsDelinerEntity.getCinemaName() : "";
            String emailTitle = "巴可发货通知：<" + code + ">-<" + crCode + ">-<" + cinemaName + ">-" + getDateStr(new Date());
            //给仓库联系人发邮件和短信
            cbsDelinerService.sendMail(cbsDelinerEntity, user, "ck", emailTitle, "mail_deliver_CSASend.ftl");
            cbsDelinerService.sendMsg(cbsDelinerEntity, user, "ck", "message_deliver_CSASend.ftl");
            //物流联系人发邮件和短信
            cbsDelinerService.sendMail(cbsDelinerEntity, user, "wl", emailTitle, "mail_deliver_CSASend.ftl");
            cbsDelinerService.sendMsg(cbsDelinerEntity, user, "wl", "message_deliver_CSASend.ftl");


        } catch (Exception e) {
            ajaxJson.setSuccess(false);
            e.getMessage();
        }
        return ajaxJson;
    }

    public CbsReturnEquipmentEntity getcbsReturnEquipmentEntiy() {

        CbsReturnEquipmentEntity cbsReturnEquipmentEntity = new CbsReturnEquipmentEntity();
        return cbsReturnEquipmentEntity;

    }

    public CbsReturnEquipmentDetailEntity getCbsReturnEquipmentDetailEntity() {

        CbsReturnEquipmentDetailEntity cbsReturnEquipmentDetailEntity = new CbsReturnEquipmentDetailEntity();
        return cbsReturnEquipmentDetailEntity;

    }

    /**
     * @author xiul
     * 2016-8-24 下午2:53:02
     * Description APP - 第三方上午 or 工程师 or 区域工程师 查询服务单代办数量
     */
    @ResponseBody
    @RequestMapping(params = "queryAppAegOrEgTodoIps")
    public AjaxJson queryAppAegOrEgTodoIps(HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        //传参，用于区分和列表查询
        String TodoNum = req.getParameter("TodoNum");
        j.setAttributes(cbsServiceService.queryAppAegOrEgTodoIps(TodoNum));
        return j;
    }

    /**
     * @author xiul
     * 2016-8-24 下午2:53:02
     * Description APP - 备件申请待办数量
     */
    @ResponseBody
    @RequestMapping(params = "queryAppEgbjsqdb")
    public AjaxJson queryAppEgbjsqdb(HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        String id = req.getParameter("id");  //服务单id
        j.setSuccess(false);
        //获取申请的备件信息
        List<CbsEquipmentApplyEntity> cbsEquipmentApplyList = systemService.findHql("from CbsEquipmentApplyEntity where serviceId='" + id + "'");
        for (CbsEquipmentApplyEntity cbsEquipmentApplyEntity : cbsEquipmentApplyList) {
            if (StringUtil.isNotEmpty(cbsEquipmentApplyEntity.getJudge()) && cbsEquipmentApplyEntity.getJudge() == 1 && cbsEquipmentApplyEntity.getStatus() == 1) {
                j.setSuccess(true);
                break;
            }
        }
        return j;
    }


    /**
     * APP故障备件验证
     *
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "queryAppGzbjyz")
    public AjaxJson queryAppGzbjyz(HttpServletRequest req) {
        AjaxJson j = new AjaxJson();
        String id = req.getParameter("id");  //服务单id
        String gzbjsn = req.getParameter("gzbjsn");  //故障备件sn
        String[] s_ns = {gzbjsn};
        if (StringUtil.isNotEmpty(id) && StringUtil.isNotEmpty(gzbjsn)) {
            if (cbsServiceService.snValiDateApp(id, s_ns)) {
                j.setSuccess(true);
                j.setMsg("验证通过");
            } else {
                j.setSuccess(false);
                j.setMsg("该序列号暂时无法核实，请联系巴可400中心确认。");
            }
        }

        return j;
    }

    /**
     * APP申请备件时，默认查询的发货信息，从服务单取
     *
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "getAPPContacts")
    public AjaxJson getAPPContacts(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        String Spareid = req.getParameter("Spareid");
        Map map = new HashMap();
        if (StringUtil.isNotEmpty(Spareid)) {
            CbsEquipmentApplyEntity cbsEquipmentApplyEntity = systemService.getEntity(CbsEquipmentApplyEntity.class, Spareid);
            if (cbsEquipmentApplyEntity != null) {
                ajaxJson.setSuccess(true);
                map.put("cbsEquipmentApplyEntity", cbsEquipmentApplyEntity);
                String cityName = "";
                String proveName = "";
                if (StringUtil.isNotEmpty(cbsEquipmentApplyEntity.getSheng()) && StringUtil.isNotEmpty(cbsEquipmentApplyEntity.getShi())) {
                    cityName += cbsEquipmentApplyEntity.getShi().getTerritoryName();
                    proveName += cbsEquipmentApplyEntity.getSheng().getTerritoryName();
                }
                map.put("cityName", cityName);
                map.put("proveName", proveName);
                ajaxJson.setAttributes(map);
            } else {
                ajaxJson.setSuccess(false);
            }
        }
        return ajaxJson;
    }

    @ResponseBody
    @RequestMapping(params = "getAPPContactsByService")
    public AjaxJson getAPPContactsByService(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        String id = req.getParameter("serviceId");
        Map map = new HashMap();
        if (StringUtil.isNotEmpty(id)) {
            String sql = "SELECT\n" +
                    "\tcbs.contacts_name AS NAME,\n" +
                    "\tcbs.contacts_phone AS cellphone,\n" +
                    "\tzy_cinema_name AS cinemaname,\n" +
                    "  IFNULL(t1.territoryname,'') as territoryname1,\n" +
                    "  IFNULL(t2.territoryname,'') as territoryname2,\n" +
                    "  IFNULL(cbs.address,'') as address\n" +
                    "FROM\n" +
                    "\tcbs_service cbs\n" +
                    "LEFT JOIN zy_contacts c ON c.id = cbs.ZY_CONTACTS_ID\n" +
                    "LEFT JOIN t_s_territory t1 on t1.id = cbs.province\n" +
                    "LEFT JOIN t_s_territory t2 on t2.id = cbs.city\n" +
                    "WHERE\n" +
                    "\tcbs.id = '" + id + "'";
            List<Map<String, Object>> list = systemService.findForJdbc(sql);
            if (list.size() > 0) {
                ajaxJson.setSuccess(true);
                ajaxJson.setAttributes(list.get(0));
            } else {
                ajaxJson.setSuccess(false);
            }
        }
        return ajaxJson;
    }

    //当前日期转化为MMdd字符转
    public String getDateStr(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("MMdd");
        String dateStr = df.format(date);
        return dateStr;
    }


    /**
     * 判断当前人是不是正确的处理人
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "judgePeople")
    public AjaxJson judgePeople(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        boolean flag = false;
        String type = req.getParameter("type");  //服务单打开的页面，（1，商务，2，区域，3工程师）
        String cbsIds = req.getParameter("cbsId");  //服务单id
        TSUser user = ResourceUtil.getSessionUserName();
        if (StringUtil.isNotEmpty(type) && StringUtil.isNotEmpty(cbsIds)) {
            for (String cbsId : cbsIds.split(",")) {
                CbsServiceEntity cbsService = systemService.get(CbsServiceEntity.class, cbsId);
                if (StringUtil.isNotEmpty(cbsService)) {
                    if (type.equals("1")) {
                        List<ZyContactsEntity> zyContactsEntities = systemService.findHql("from ZyContactsEntity where tsBaseUser.id = ?", user.getId());
                        if (zyContactsEntities.size() > 0 && StringUtil.isNotEmpty(zyContactsEntities)) {
                            if (cbsService.getZyContacts().equals(zyContactsEntities.get(0).getId())) {
                                flag = true;
                            }
                        }
                    }
                    if (type.equals("2")) {
                        List<ZyEngineerEntity> egs = systemService.findByProperty(ZyEngineerEntity.class, "tsBaseUser.id", user.getId());
                        if (egs.size() > 0 && StringUtil.isNotEmpty(egs)) {
                            if (egs.get(0).getId().equals(cbsService.getAreaEngineer())) {
                                flag = true;
                            }
                        }
                    }
                    if (type.equals("3")) {
                        List<ZyEngineerEntity> egs = systemService.findByProperty(ZyEngineerEntity.class, "tsBaseUser.id", user.getId());
                        if (egs.size() > 0 && StringUtil.isNotEmpty(egs)) {
                            if (egs.get(0).getId().equals(cbsService.getEngineer())) {
                                flag = true;
                            }
                        }
                    }
                }
            }
        }
        ajaxJson.setSuccess(flag);
        return ajaxJson;
    }


    /**
     * APP端现场照片回显
     *
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "getcompleteFile")
    public AjaxJson getcompleteFile(HttpServletRequest req) {
        AjaxJson ajaxJson = new AjaxJson();
        String cbsId = req.getParameter("fileBeanId");
        String type = req.getParameter("type");
        String zptype = req.getParameter("zptype"); /*yqfx qt*/
        List<Map<String, Object>> zyFileLogList = zyFileLogServiceI.getcompleteFile(cbsId, type, zptype);
        ajaxJson.setObj(zyFileLogList);
        return ajaxJson;
    }

    //申请备件邮件提醒
    public void sendToCSA(CbsServiceEntity cbsServiceEntity, List<String> listbySql2, TSUser user) {
        //获取服务商信息
        List<String> shortnameList = systemService.findListbySql("select d.shortname from t_s_depart d left join cbs_service cbs on d.org_code = cbs.service_provider_code where cbs.id='" + cbsServiceEntity.getId() + "'");
        String shortname = "";
        if (shortnameList.size() != 0) {
            shortname = shortnameList.get(0);
        }
        String emailTital = "备件申请审批提醒:<" + shortname + ">-<" + listbySql2.get(0) + ">-<" + cbsServiceEntity.getLevel() + ">-<" + cbsServiceEntity.getServiceType1().getName() + "," + cbsServiceEntity.getServiceType2().getName() + ">-<" + cbsServiceEntity.getCode() + ">" + "-" + getDateStr(new Date());
        String emailContent = "400同事你好，服务单" + cbsServiceEntity.getCode() + "提交备件申请，备件申请单号:" + listbySql2.get(0) + ",请及时审批。\n" + "备件申请人：<" +
                shortname + ">" + "<" + user.getRealName() + ">" + "<" + user.getMobilePhone() + ">" + "具体内容请查看http://cbs.cfg-barco.com\n" +
                "\n" +
                "* 该邮件请勿回复";
        // 18/5/17 添加条件，必须是正常状态用户
        List<String> listbySql = systemService.findListbySql("select email from t_s_user u LEFT JOIN t_s_role_user ru ON u.id=ru.userid LEFT JOIN t_s_role r ON ru.roleid=r.id LEFT JOIN t_s_base_user b on b.id = u.id where b.`status` = '" + Globals.User_Normal + "' and r.rolecode='" + StaticValue.CBS_HD_ROLE_CODE + "'");
        for (int i = 0; i < listbySql.size(); i++) {
            SendMailUtil.sendeMail(listbySql.get(i), emailTital, emailContent, systemService);
        }
    }


    /**
     * APP端生成二维码并按照条件回显
     *
     * @return 二维码地址
     */
    @ResponseBody
    @RequestMapping(params = "getAppServiceQrCode")
    public AjaxJson getAppServiceQrCode(HttpServletRequest req) {
        String cbsId = req.getParameter("planIds");
        AjaxJson ajaxJson = new AjaxJson();
        ZyFileLogEntity fileentity = cbsServiceService.getAppServiceQrCode(cbsId);
        ajaxJson.setObj(fileentity.getId());
        return ajaxJson;
    }


    /**
     * 根据服务单id  判断填写完工单按钮是否显示
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "judgeAppWrite")
    public AjaxJson judgeAppWrite(HttpServletRequest req) {
        AjaxJson ajax = new AjaxJson();
        String cbsId = req.getParameter("planIds");
        //获取到货异常
        List<ArrivalofabnormalEntity> arrivalOfAbnormal = systemService.findByProperty(ArrivalofabnormalEntity.class, "serviceId.id", cbsId);
        if (StringUtil.isNotEmpty(arrivalOfAbnormal) && arrivalOfAbnormal.size() > 0) {
            ajax.setSuccess(true);
        } else {
            ajax.setSuccess(false);
        }
        return ajax;
    }

    /**
     * 获取现场照片类型
     *
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(params = "getimgCase")
    public AjaxJson getimgCase(HttpServletRequest req) {
        AjaxJson ajax = new AjaxJson();
        List<TSType> photos = systemService.findHql("FROM TSType where TSTypegroup.typegroupcode='photoTypesOf'");
        ajax.setObj(photos);
        return ajax;
    }


    /**
     * @return
     * @author xiul
     * 2016-5-5 下午8:05:32
     * Description 问题分析报表页
     */
    @RequestMapping(params = "goCbsServiceLine")
    public ModelAndView goZyInspectionProblemAnalysisReport(HttpServletRequest req) {
        List<String> years = cbsServiceService.queryYearsInService();
        req.setAttribute("years", years);
        return new ModelAndView("com/zybk/cbsservice/cbsServiceLine");
    }


    /**
     * 院线服务情况报表 - 列表数据
     *
     * @param req
     * @param year          年
     * @param bp            BP
     * @param intheatername 院线
     * @return AjaxJson
     */
    @ResponseBody
    @RequestMapping(params = "getIpProblemReportData")
    public AjaxJson getIpProblemReportData(HttpServletRequest req, @RequestParam(value = "year") String year,
                                           @RequestParam(value = "bp", defaultValue = "") String bp, @RequestParam(value = "intheatername", defaultValue = "") String intheatername) {
        AjaxJson j = new AjaxJson();
        try {
            Map<String, List<Map<String, Integer>>> temperatureZx = cbsServiceService.getIpProblemReportData("1", year, intheatername, bp);
            Map<String, List<Map<String, Integer>>> reMap = new HashMap<>();
            reMap.put("temperatureZx", temperatureZx.get("咨询"));
            reMap.put("temperatureSm", temperatureZx.get("上门服务"));
            reMap.put("temperatureYc", temperatureZx.get("远程服务"));
            j.setObj(reMap);
        } catch (Exception e) {
            j.setMsg("查询数据异常");
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }

    /**
     * 院线服务状态报表 - 列表数据
     *
     * @param req
     * @param bp  BP
     * @return AjaxJson
     */
    @ResponseBody
    @RequestMapping(params = "getStatusTableData")
    public AjaxJson getStatusTableData(HttpServletRequest req, @RequestParam(value = "bp", defaultValue = "") String bp, @RequestParam(value = "intheatername", defaultValue = "") String intheatername) {
        AjaxJson j = new AjaxJson();
        try {
            Map<String, Object> temperature = cbsServiceService.getStatusTableData(intheatername, bp);
            j.setObj(temperature);
        } catch (Exception e) {
            j.setMsg("查询数据异常");
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }

    /**
     * 根据报表数量获取服务单内容
     *
     * @return
     */
    @RequestMapping(params = "getDetailCbsReport")
    public ModelAndView getDetailCbsReport(HttpServletRequest request) {
        String paramsString = "";
        String year = request.getParameter("year");
        String month = request.getParameter("month");
        String exType = request.getParameter("exType");
        Map param = new HashMap<>();
        String type1 = "故障维修";
        String type2 = "咨询";

        if (StringUtil.isNotEmpty(year)) {//year是基础查询条件，这里根据year 和 ipEndTimeYear 来区分
            paramsString = "&year=" + year + "&month=" + month;
        }

        if (StringUtil.isNotEmpty(exType)) {
            if (exType.equals("1")) {  //咨询
                paramsString = "&serviceTypeName=" + type2;

            }
            if (exType.equals("2")) {  //上门
                paramsString = "&serviceTypeName=" + type1;
                List<String> statusList = new ArrayList<>();
                statusList.add(StaticValue.clz);
                statusList.add(StaticValue.ywc);
                statusList.add(StaticValue.yqx);
                paramsString = "&statusList=" + statusList;

            }
            if (exType.equals("3")) {  //远程
                paramsString = "&serviceTypeName=" + type1;
                List<String> statusList = new ArrayList<>();
                statusList.add(StaticValue.dcl);
                statusList.add(StaticValue.ysl);
                paramsString = "&statusList= " + statusList;
            }
        }
        request.setAttribute("params", paramsString);
        return new ModelAndView("com/zybk/cbsservice/cbsServiceList");
    }

    /*院线设备情况*/
    @RequestMapping(params = "goFacilitiesService")
    public ModelAndView goFacilitiesService(HttpServletRequest req) {
        return new ModelAndView("com/zybk/cbsservice/facilitiesService");
    }

    /*设备整体维保情况*/
    @ResponseBody
    @RequestMapping(params = "getFacilitiesZtTableData")
    public AjaxJson getFacilitiesZtTableData(HttpServletRequest req, @RequestParam(value = "cdateBegin", defaultValue = "") String cdateBegin, @RequestParam(value = "cdateEnd", defaultValue = "") String cdateEnd, @RequestParam(value = "bp", defaultValue = "") String bp, @RequestParam(value = "intheatername", defaultValue = "") String intheatername) {
        AjaxJson j = new AjaxJson();
        try {
            Map<String, List<Map<String, Object>>> temperature = cbsServiceService.getFacilitiesZtTableData(cdateBegin, cdateEnd, intheatername, bp);
            j.setObj(temperature);
        } catch (Exception e) {
            j.setMsg("查询数据异常");
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }

    /*出保设备情况报表*/
    @ResponseBody
    @RequestMapping(params = "getFacilitiesCbTableData")
    public AjaxJson getFacilitiesCbTableData(HttpServletRequest req, @RequestParam(value = "cdateBegin", defaultValue = "") String cdateBegin, @RequestParam(value = "cdateEnd", defaultValue = "") String cdateEnd, @RequestParam(value = "bp", defaultValue = "") String bp, @RequestParam(value = "intheatername", defaultValue = "") String intheatername) {
        AjaxJson j = new AjaxJson();
        try {
            Map<String, List<Map<String, Object>>> temperature = cbsServiceService.getFacilitiesCbTableData(cdateBegin, cdateEnd, intheatername, bp);
            j.setObj(temperature);
        } catch (Exception e) {
            j.setMsg("查询数据异常");
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }

    /*院线机型配比报表*/
    @ResponseBody
    @RequestMapping(params = "getEsHighChartsOfCbData")
    public AjaxJson getEsHighChartsOfCbData(HttpServletRequest req, @RequestParam(value = "cdateBegin", defaultValue = "") String cdateBegin, @RequestParam(value = "cdateEnd", defaultValue = "") String cdateEnd, @RequestParam(value = "bp", defaultValue = "") String bp, @RequestParam(value = "intheatername", defaultValue = "") String intheatername) {
        AjaxJson j = new AjaxJson();
        try {
            Map<String, String> temperature = cbsServiceService.getEsHighChartsOfCbData(cdateBegin, cdateEnd, intheatername, bp);
            j.setObj(temperature);
        } catch (Exception e) {
            j.setMsg("查询数据异常");
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }

}
